home *** CD-ROM | disk | FTP | other *** search
/ Amiga Games Extra 1996 September / Amiga Games Extra CD-ROM 9-1996.iso / userbox / publicdomain / vim-4.2 / src / cmdline.c < prev    next >
C/C++ Source or Header  |  1996-06-17  |  125KB  |  5,383 lines

  1. /* vi:set ts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved        by Bram Moolenaar
  4.  *
  5.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  6.  * Do ":help credits" in Vim to see a list of people who contributed.
  7.  */
  8.  
  9. /*
  10.  * cmdline.c: functions for reading in the command line and executing it
  11.  */
  12.  
  13. #include "vim.h"
  14. #include "globals.h"
  15. #include "proto.h"
  16. #include "option.h"
  17. #include "cmdtab.h"
  18. #include "ops.h"            /* included because we call functions in ops.c */
  19. #ifdef HAVE_FCNTL_H
  20. # include <fcntl.h>            /* for chdir() */
  21. #endif
  22.  
  23. /*
  24.  * variables shared between getcmdline() and redrawcmdline()
  25.  */
  26. static char_u    *cmdbuff;        /* pointer to command line buffer */
  27. static int         cmdbufflen;    /* length of cmdbuff */
  28. static int         cmdlen;        /* number of chars on command line */
  29. static int         cmdpos;        /* current cursor position */
  30. static int         cmdspos;        /* cursor column on screen */
  31. static int         cmdfirstc;     /* ':', '/' or '?' */
  32.  
  33. /*
  34.  * Typing mode on the command line.  Shared by getcmdline() and
  35.  * put_on_cmdline().
  36.  */
  37. static int        overstrike = FALSE;    /* typing mode */
  38.  
  39. /*
  40.  * The next two variables contain the bounds of any range given in a command.
  41.  * They are set by do_cmdline().
  42.  */
  43. static linenr_t     line1, line2;
  44.  
  45. static int            forceit;
  46. static int            regname;
  47. static int            quitmore = 0;
  48. static int          cmd_numfiles = -1;      /* number of files found by
  49.                                                     filename completion */
  50. /*
  51.  * There are two history tables:
  52.  * 0: colon commands
  53.  * 1: search commands
  54.  */
  55. static char_u        **(history[2]) = {NULL, NULL};    /* history tables */
  56. static int            hisidx[2] = {-1, -1};            /* last entered entry */
  57. static int            hislen = 0;         /* actual lengt of history tables */
  58.  
  59. #ifdef RIGHTLEFT
  60. static int            cmd_hkmap = 0;        /* Hebrew mapping during command line */
  61. #endif
  62.  
  63. static void        init_history __ARGS((void));
  64.  
  65. static int        is_in_history __ARGS((int, char_u *, int));
  66. static void        putcmdline __ARGS((int));
  67. static void        redrawcmd __ARGS((void));
  68. static void        cursorcmd __ARGS((void));
  69. static int        ccheck_abbr __ARGS((int));
  70. static char_u    *do_one_cmd __ARGS((char_u **, int *, int));
  71. static int        buf_write_all __ARGS((BUF *));
  72. static int        do_write __ARGS((char_u *, int));
  73. static char_u    *getargcmd __ARGS((char_u **));
  74. static void        backslash_halve __ARGS((char_u *p, int expand_wildcards));
  75. static void        do_make __ARGS((char_u *));
  76. static int        do_arglist __ARGS((char_u *));
  77. static int        is_backslash __ARGS((char_u *str));
  78. static int        check_readonly __ARGS((void));
  79. static int        check_changed __ARGS((BUF *, int, int));
  80. static int        check_changed_any __ARGS((void));
  81. static int        check_more __ARGS((int));
  82. static void        vim_strncpy __ARGS((char_u *, char_u *, int));
  83. static int        nextwild __ARGS((int));
  84. static int        showmatches __ARGS((char_u *));
  85. static linenr_t get_address __ARGS((char_u **));
  86. static void        set_expand_context __ARGS((int, char_u *));
  87. static char_u    *set_one_cmd_context __ARGS((int, char_u *));
  88. static int        ExpandFromContext __ARGS((char_u *, int *, char_u ***, int, int));
  89. static int        ExpandCommands __ARGS((regexp *, int *, char_u ***));
  90.  
  91. /*
  92.  * init_history() - initialize the command line history
  93.  */
  94.     static void
  95. init_history()
  96. {
  97.     int        newlen;            /* new length of history table */
  98.     char_u    **temp;
  99.     register int i;
  100.     int        j;
  101.     int        type;
  102.  
  103.     /*
  104.      * If size of history table changed, reallocate it
  105.      */
  106.     newlen = (int)p_hi;
  107.     if (newlen != hislen)                        /* history length changed */
  108.     {
  109.         for (type = 0; type <= 1; ++type)        /* adjust both history tables */
  110.         {
  111.             if (newlen)
  112.                 temp = (char_u **)lalloc((long_u)(newlen * sizeof(char_u *)),
  113.                                     TRUE);
  114.             else
  115.                 temp = NULL;
  116.             if (newlen == 0 || temp != NULL)
  117.             {
  118.                 if (hisidx[type] < 0)            /* there are no entries yet */
  119.                 {
  120.                     for (i = 0; i < newlen; ++i)
  121.                         temp[i] = NULL;
  122.                 }
  123.                 else if (newlen > hislen)        /* array becomes bigger */
  124.                 {
  125.                     for (i = 0; i <= hisidx[type]; ++i)
  126.                         temp[i] = history[type][i];
  127.                     j = i;
  128.                     for ( ; i <= newlen - (hislen - hisidx[type]); ++i)
  129.                         temp[i] = NULL;
  130.                     for ( ; j < hislen; ++i, ++j)
  131.                         temp[i] = history[type][j];
  132.                 }
  133.                 else                            /* array becomes smaller or 0 */
  134.                 {
  135.                     j = hisidx[type];
  136.                     for (i = newlen - 1; ; --i)
  137.                     {
  138.                         if (i >= 0)                /* copy newest entries */
  139.                             temp[i] = history[type][j];
  140.                         else                    /* remove older entries */
  141.                             vim_free(history[type][j]);
  142.                         if (--j < 0)
  143.                             j = hislen - 1;
  144.                         if (j == hisidx[type])
  145.                             break;
  146.                     }
  147.                     hisidx[type] = newlen - 1;
  148.                 }
  149.                 vim_free(history[type]);
  150.                 history[type] = temp;
  151.             }
  152.         }
  153.         hislen = newlen;
  154.     }
  155. }
  156.  
  157. /*
  158.  * check if command line 'str' is already in history
  159.  * 'type' is 0 for ':' commands, '1' for search commands
  160.  * if 'move_to_front' is TRUE, matching entry is moved to end of history
  161.  */
  162.     static int
  163. is_in_history(type, str, move_to_front)
  164.     int        type;
  165.     char_u    *str;
  166.     int        move_to_front;        /* Move the entry to the front if it exists */
  167. {
  168.     int        i;
  169.     int        last_i = -1;
  170.  
  171.     if (hisidx[type] < 0)
  172.         return FALSE;
  173.     i = hisidx[type];
  174.     do
  175.     {
  176.         if (history[type][i] == NULL)
  177.             return FALSE;
  178.         if (STRCMP(str, history[type][i]) == 0)
  179.         {
  180.             if (!move_to_front)
  181.                 return TRUE;
  182.             last_i = i;
  183.             break;
  184.         }
  185.         if (--i < 0)
  186.             i = hislen - 1;
  187.     } while (i != hisidx[type]);
  188.  
  189.     if (last_i >= 0)
  190.     {
  191.         str = history[type][i];
  192.         while (i != hisidx[type])
  193.         {
  194.             if (++i >= hislen)
  195.                 i = 0;
  196.             history[type][last_i] = history[type][i];
  197.             last_i = i;
  198.         }
  199.         history[type][i] = str;
  200.         return TRUE;
  201.     }
  202.     return FALSE;
  203. }
  204.  
  205. /*
  206.  * Add the given string to the given history.  If the string is already in the
  207.  * history then it is moved to the front.  histype may be 0 for the ':'
  208.  * history, or 1 for the '/' history.
  209.  */
  210.     void
  211. add_to_history(histype, new_entry)
  212.     int        histype;
  213.     char_u    *new_entry;
  214. {
  215.     if (hislen != 0 && !is_in_history(histype, new_entry, TRUE))
  216.     {
  217.         if (++hisidx[histype] == hislen)
  218.             hisidx[histype] = 0;
  219.         vim_free(history[histype][hisidx[histype]]);
  220.         history[histype][hisidx[histype]] = strsave(new_entry);
  221.     }
  222. }
  223.  
  224.  
  225. /*
  226.  * getcmdline() - accept a command line starting with ':', '/', or '?'
  227.  *
  228.  * The line is collected in cmdbuff, which is reallocated to fit the command
  229.  * line.
  230.  *
  231.  * Return pointer to allocated string if there is a commandline, NULL
  232.  * otherwise.
  233.  */
  234.  
  235.     char_u *
  236. getcmdline(firstc, count)
  237.     int            firstc;     /* either ':', '/', or '?' */
  238.     long        count;        /* only used for incremental search */
  239. {
  240.     register int         c;
  241. #ifdef DIGRAPHS
  242.              int        cc;
  243. #endif
  244.     register int        i;
  245.              int        j;
  246.              char_u        *p;
  247.              int        hiscnt;                /* current history line in use */
  248.              char_u        *lookfor = NULL;    /* string to match */
  249.              int        gotesc = FALSE;        /* TRUE when <ESC> just typed */
  250.              int        do_abbr;            /* when TRUE check for abbr. */
  251.              int        histype;            /* history type to be used */
  252.              FPOS        old_cursor;
  253.              colnr_t    old_curswant;
  254.              int        did_incsearch = FALSE;
  255.              int        incsearch_postponed = FALSE;
  256.              int        save_msg_scroll = msg_scroll;
  257.              int        some_key_typed = FALSE;    /* one of the keys was typed */
  258. #ifdef USE_MOUSE
  259.              /* mouse drag and release events are ignored, unless they are
  260.               * preceded with a mouse down event */
  261.              int        ignore_drag_release = TRUE;
  262. #endif
  263.  
  264.     overstrike = FALSE;                        /* always start in insert mode */
  265.     old_cursor = curwin->w_cursor;            /* needs to be restored later */
  266.     old_curswant = curwin->w_curswant;
  267. /*
  268.  * set some variables for redrawcmd()
  269.  */
  270.     cmdfirstc = firstc;
  271.     alloc_cmdbuff(0);                    /* allocate initial cmdbuff */
  272.     if (cmdbuff == NULL)
  273.         return NULL;                    /* out of memory */
  274.     cmdlen = cmdpos = 0;
  275.     cmdspos = 1;
  276.     State = CMDLINE;
  277. #ifdef USE_MOUSE
  278.     setmouse();
  279. #endif
  280.     gotocmdline(TRUE);
  281.     msg_outchar(firstc);
  282.     /*
  283.      * Avoid scrolling when called by a recursive do_cmdline(), e.g. when doing
  284.      * ":@0" when register 0 doesn't contain a CR.
  285.      */
  286.     msg_scroll = FALSE;
  287.  
  288.     init_history();
  289.     hiscnt = hislen;            /* set hiscnt to impossible history value */
  290.     histype = (firstc == ':' ? 0 : 1);
  291.  
  292. #ifdef DIGRAPHS
  293.     do_digraph(-1);                /* init digraph typahead */
  294. #endif
  295.  
  296.     /* collect the command string, handling editing keys */
  297.     for (;;)
  298.     {
  299.         cursorcmd();            /* set the cursor on the right spot */
  300.         c = vgetc();
  301.         if (KeyTyped)
  302.         {
  303.             some_key_typed = TRUE;
  304. #ifdef RIGHTLEFT
  305.             if (cmd_hkmap)
  306.                 c = hkmap(c);
  307. #endif
  308.         }
  309.         if (c == Ctrl('C'))
  310.             got_int = FALSE;    /* ignore got_int when CTRL-C was typed here */
  311.  
  312.             /* free old command line when finished moving around in the
  313.              * history list */
  314.         if (lookfor && c != K_S_DOWN && c != K_S_UP &&
  315.                 c != K_DOWN && c != K_UP &&
  316.                 c != K_PAGEDOWN && c != K_PAGEUP &&
  317.                 (cmd_numfiles > 0 || (c != Ctrl('P') && c != Ctrl('N'))))
  318.         {
  319.             vim_free(lookfor);
  320.             lookfor = NULL;
  321.         }
  322.  
  323.         /*
  324.          * <S-Tab> works like CTRL-P (unless 'wc' is <S-Tab>).
  325.          */
  326.         if (c != p_wc && c == K_S_TAB)
  327.             c = Ctrl('P');
  328.  
  329.             /* free expanded names when finished walking through matches */
  330.         if (cmd_numfiles != -1 && !(c == p_wc && KeyTyped) && c != Ctrl('N') &&
  331.                         c != Ctrl('P') && c != Ctrl('A') && c != Ctrl('L'))
  332.             (void)ExpandOne(NULL, NULL, 0, WILD_FREE);
  333.  
  334. #ifdef DIGRAPHS
  335.         c = do_digraph(c);
  336. #endif
  337.  
  338.         if (c == '\n' || c == '\r' || (c == ESC && (!KeyTyped || 
  339.                                          vim_strchr(p_cpo, CPO_ESC) != NULL)))
  340.         {
  341.             if (ccheck_abbr(c + ABBR_OFF))
  342.                 goto cmdline_changed;
  343.             outchar('\r');        /* show that we got the return */
  344.             screen_cur_col = 0;
  345.             flushbuf();
  346.             break;
  347.         }
  348.  
  349.             /* hitting <ESC> twice means: abandon command line */
  350.             /* wildcard expansion is only done when the key is really typed,
  351.              * not when it comes from a macro */
  352.         if (c == p_wc && !gotesc && KeyTyped)
  353.         {
  354.             if (cmd_numfiles > 0)    /* typed p_wc twice */
  355.                 i = nextwild(WILD_NEXT);
  356.             else                    /* typed p_wc first time */
  357.                 i = nextwild(WILD_EXPAND_KEEP);
  358.             if (c == ESC)
  359.                 gotesc = TRUE;
  360.             if (i)
  361.                 goto cmdline_changed;
  362.         }
  363.         gotesc = FALSE;
  364.  
  365.         if (c == NUL || c == K_ZERO)        /* NUL is stored as NL */
  366.             c = NL;
  367.  
  368.         do_abbr = TRUE;            /* default: check for abbreviation */
  369.         switch (c)
  370.         {
  371.         case K_BS:
  372.         case Ctrl('H'):
  373.         case K_DEL:
  374.         case Ctrl('W'):
  375.                 /*
  376.                  * delete current character is the same as backspace on next
  377.                  * character, except at end of line
  378.                  */
  379.                 if (c == K_DEL && cmdpos != cmdlen)
  380.                     ++cmdpos;
  381.                 if (cmdpos > 0)
  382.                 {
  383.                     j = cmdpos;
  384.                     if (c == Ctrl('W'))
  385.                     {
  386.                         while (cmdpos && vim_isspace(cmdbuff[cmdpos - 1]))
  387.                             --cmdpos;
  388.                         i = iswordchar(cmdbuff[cmdpos - 1]);
  389.                         while (cmdpos && !vim_isspace(cmdbuff[cmdpos - 1]) &&
  390.                                          iswordchar(cmdbuff[cmdpos - 1]) == i)
  391.                             --cmdpos;
  392.                     }
  393.                     else
  394.                         --cmdpos;
  395.                     cmdlen -= j - cmdpos;
  396.                     i = cmdpos;
  397.                     while (i < cmdlen)
  398.                         cmdbuff[i++] = cmdbuff[j++];
  399.                     redrawcmd();
  400.                 }
  401.                 else if (cmdlen == 0 && c != Ctrl('W'))
  402.                 {
  403.                     vim_free(cmdbuff);        /* no commandline to return */
  404.                     cmdbuff = NULL;
  405.                     msg_pos(-1, 0);
  406.                     msg_outchar(' ');    /* delete ':' */
  407.                     redraw_cmdline = TRUE;
  408.                     goto returncmd;     /* back to cmd mode */
  409.                 }
  410.                 goto cmdline_changed;
  411.  
  412.         case K_INS:
  413.                 overstrike = !overstrike;
  414.                 /* should change shape of cursor */
  415.                 goto cmdline_not_changed;
  416.  
  417. /*        case '@':    only in very old vi */
  418.         case Ctrl('U'):
  419.                 cmdpos = 0;
  420.                 cmdlen = 0;
  421.                 cmdspos = 1;
  422.                 redrawcmd();
  423.                 goto cmdline_changed;
  424.  
  425.         case ESC:        /* get here if p_wc != ESC or when ESC typed twice */
  426.         case Ctrl('C'):
  427.                 gotesc = TRUE;        /* will free cmdbuff after putting it in
  428.                                         history */
  429.                 goto returncmd;     /* back to cmd mode */
  430.  
  431.         case Ctrl('R'):                /* insert register */
  432.                 putcmdline('"');
  433.                 ++no_mapping;
  434.                   c = vgetc();
  435.                 --no_mapping;
  436.                 if (c != ESC)        /* use ESC to cancel inserting register */
  437.                     cmdline_paste(c);
  438.                 redrawcmd();
  439.                 goto cmdline_changed;
  440.  
  441.         case Ctrl('D'):
  442.             {
  443.                 if (showmatches(cmdbuff) == FAIL)
  444.                     break;        /* Use ^D as normal char instead */
  445.  
  446.                 redrawcmd();
  447.                 continue;        /* don't do incremental search now */
  448.             }
  449.  
  450.         case K_RIGHT:
  451.         case K_S_RIGHT:
  452.                 do
  453.                 {
  454.                         if (cmdpos >= cmdlen)
  455.                                 break;
  456.                         cmdspos += charsize(cmdbuff[cmdpos]);
  457.                         ++cmdpos;
  458.                 }
  459.                 while (c == K_S_RIGHT && cmdbuff[cmdpos] != ' ');
  460.                 goto cmdline_not_changed;
  461.  
  462.         case K_LEFT:
  463.         case K_S_LEFT:
  464.                 do
  465.                 {
  466.                         if (cmdpos <= 0)
  467.                                 break;
  468.                         --cmdpos;
  469.                         cmdspos -= charsize(cmdbuff[cmdpos]);
  470.                 }
  471.                 while (c == K_S_LEFT && cmdbuff[cmdpos - 1] != ' ');
  472.                 goto cmdline_not_changed;
  473.  
  474. #ifdef USE_MOUSE
  475.         case K_MIDDLEDRAG:
  476.         case K_MIDDLERELEASE:
  477.         case K_IGNORE:
  478.                 goto cmdline_not_changed;    /* Ignore mouse */
  479.  
  480.         case K_MIDDLEMOUSE:
  481. # ifdef USE_GUI
  482.                 /* When GUI is active, also paste when 'mouse' is empty */
  483.                 if (!gui.in_use)
  484. # endif
  485.                     if (!mouse_has(MOUSE_COMMAND))
  486.                         goto cmdline_not_changed;    /* Ignore mouse */
  487. # ifdef USE_GUI
  488.                 if (gui.in_use && yankbuffer == 0)
  489.                     cmdline_paste('*');
  490.                 else
  491. # endif
  492.                     cmdline_paste(yankbuffer);
  493.                 redrawcmd();
  494.                 goto cmdline_changed;
  495.  
  496.         case K_LEFTDRAG:
  497.         case K_LEFTRELEASE:
  498.         case K_RIGHTDRAG:
  499.         case K_RIGHTRELEASE:
  500.                 if (ignore_drag_release)
  501.                     goto cmdline_not_changed;
  502.                 /* FALLTHROUGH */
  503.         case K_LEFTMOUSE:
  504.         case K_RIGHTMOUSE:
  505.                 if (c == K_LEFTRELEASE || c == K_RIGHTRELEASE)
  506.                     ignore_drag_release = TRUE;
  507.                 else
  508.                     ignore_drag_release = FALSE;
  509. # ifdef USE_GUI
  510.                 /* When GUI is active, also move when 'mouse' is empty */
  511.                 if (!gui.in_use)
  512. # endif
  513.                     if (!mouse_has(MOUSE_COMMAND))
  514.                         goto cmdline_not_changed;    /* Ignore mouse */
  515.                 cmdspos = 1;
  516.                 for (cmdpos = 0; cmdpos < cmdlen; ++cmdpos)
  517.                 {
  518.                     i = charsize(cmdbuff[cmdpos]);
  519.                     if (mouse_row <= cmdline_row + cmdspos / Columns &&
  520.                                         mouse_col < cmdspos % Columns + i)
  521.                         break;
  522.                     cmdspos += i;
  523.                 }
  524.                 goto cmdline_not_changed;
  525. #endif    /* USE_MOUSE */
  526.  
  527. #ifdef USE_GUI
  528.         case K_SCROLLBAR:
  529.                 if (!msg_scrolled)
  530.                 {
  531.                     gui_do_scroll();
  532.                     redrawcmd();
  533.                 }
  534.                 goto cmdline_not_changed;
  535.  
  536.         case K_HORIZ_SCROLLBAR:
  537.                 if (!msg_scrolled)
  538.                 {
  539.                     gui_do_horiz_scroll();
  540.                     redrawcmd();
  541.                 }
  542.                 goto cmdline_not_changed;
  543. #endif
  544.  
  545.         case Ctrl('B'):        /* begin of command line */
  546.         case K_HOME:
  547.                 cmdpos = 0;
  548.                 cmdspos = 1;
  549.                 goto cmdline_not_changed;
  550.  
  551.         case Ctrl('E'):        /* end of command line */
  552.         case K_END:
  553.                 cmdpos = cmdlen;
  554.                 cmdbuff[cmdlen] = NUL;
  555.                 cmdspos = strsize(cmdbuff) + 1;
  556.                 goto cmdline_not_changed;
  557.  
  558.         case Ctrl('A'):        /* all matches */
  559.                 if (!nextwild(WILD_ALL))
  560.                     break;
  561.                 goto cmdline_changed;
  562.  
  563.         case Ctrl('L'):        /* longest common part */
  564.                 if (!nextwild(WILD_LONGEST))
  565.                     break;
  566.                 goto cmdline_changed;
  567.  
  568.         case Ctrl('N'):        /* next match */
  569.         case Ctrl('P'):        /* previous match */
  570.                 if (cmd_numfiles > 0)
  571.                 {
  572.                     if (!nextwild((c == Ctrl('P')) ? WILD_PREV : WILD_NEXT))
  573.                         break;
  574.                     goto cmdline_changed;
  575.                 }
  576.  
  577.         case K_UP:
  578.         case K_DOWN:
  579.         case K_S_UP:
  580.         case K_S_DOWN:
  581.         case K_PAGEUP:
  582.         case K_PAGEDOWN:
  583.                 if (hislen == 0)        /* no history */
  584.                     goto cmdline_not_changed;
  585.  
  586.                 i = hiscnt;
  587.             
  588.                 /* save current command string so it can be restored later */
  589.                 cmdbuff[cmdpos] = NUL;
  590.                 if (lookfor == NULL && (lookfor = strsave(cmdbuff)) == NULL)
  591.                     goto cmdline_not_changed;
  592.  
  593.                 j = STRLEN(lookfor);
  594.                 for (;;)
  595.                 {
  596.                         /* one step backwards */
  597.                     if (c == K_UP || c == K_S_UP || c == Ctrl('P') ||
  598.                             c == K_PAGEUP)
  599.                     {
  600.                         if (hiscnt == hislen)    /* first time */
  601.                             hiscnt = hisidx[histype];
  602.                         else if (hiscnt == 0 && hisidx[histype] != hislen - 1)
  603.                             hiscnt = hislen - 1;
  604.                         else if (hiscnt != hisidx[histype] + 1)
  605.                             --hiscnt;
  606.                         else                    /* at top of list */
  607.                         {
  608.                             hiscnt = i;
  609.                             break;
  610.                         }
  611.                     }
  612.                     else    /* one step forwards */
  613.                     {
  614.                                     /* on last entry, clear the line */
  615.                         if (hiscnt == hisidx[histype])
  616.                         {
  617.                             hiscnt = hislen;
  618.                             break;
  619.                         }
  620.                                     /* not on a history line, nothing to do */
  621.                         if (hiscnt == hislen)
  622.                             break;
  623.                         if (hiscnt == hislen - 1)    /* wrap around */
  624.                             hiscnt = 0;
  625.                         else
  626.                             ++hiscnt;
  627.                     }
  628.                     if (hiscnt < 0 || history[histype][hiscnt] == NULL)
  629.                     {
  630.                         hiscnt = i;
  631.                         break;
  632.                     }
  633.                     if ((c != K_UP && c != K_DOWN) || hiscnt == i ||
  634.                             STRNCMP(history[histype][hiscnt],
  635.                                                     lookfor, (size_t)j) == 0)
  636.                         break;
  637.                 }
  638.  
  639.                 if (hiscnt != i)        /* jumped to other entry */
  640.                 {
  641.                     vim_free(cmdbuff);
  642.                     if (hiscnt == hislen)
  643.                         p = lookfor;    /* back to the old one */
  644.                     else
  645.                         p = history[histype][hiscnt];
  646.  
  647.                     alloc_cmdbuff((int)STRLEN(p));
  648.                     if (cmdbuff == NULL)
  649.                         goto returncmd;
  650.                     STRCPY(cmdbuff, p);
  651.  
  652.                     cmdpos = cmdlen = STRLEN(cmdbuff);
  653.                     redrawcmd();
  654.                     goto cmdline_changed;
  655.                 }
  656.                 beep_flush();
  657.                 goto cmdline_not_changed;
  658.  
  659.         case Ctrl('V'):
  660.         case Ctrl('Q'):
  661. #ifdef USE_MOUSE
  662.                 ignore_drag_release = TRUE;
  663. #endif
  664.                 putcmdline('^');
  665.                 c = get_literal();            /* get next (two) character(s) */
  666.                 do_abbr = FALSE;            /* don't do abbreviation now */
  667.                 break;
  668.  
  669. #ifdef DIGRAPHS
  670.         case Ctrl('K'):
  671. #ifdef USE_MOUSE
  672.                 ignore_drag_release = TRUE;
  673. #endif
  674.                 putcmdline('?');
  675.                 ++no_mapping;
  676.                 ++allow_keys;
  677.                   c = vgetc();
  678.                 --no_mapping;
  679.                 --allow_keys;
  680.                 if (c != ESC)                /* ESC cancels CTRL-K */
  681.                 {
  682.                     if (IS_SPECIAL(c))            /* insert special key code */
  683.                         break;
  684.                     if (charsize(c) == 1)
  685.                         putcmdline(c);
  686.                     ++no_mapping;
  687.                     ++allow_keys;
  688.                     cc = vgetc();
  689.                     --no_mapping;
  690.                     --allow_keys;
  691.                     if (cc != ESC)            /* ESC cancels CTRL-K */
  692.                     {
  693.                         c = getdigraph(c, cc, TRUE);
  694.                         break;
  695.                     }
  696.                 }
  697.                 redrawcmd();
  698.                 goto cmdline_not_changed;
  699. #endif /* DIGRAPHS */
  700.  
  701. #ifdef RIGHTLEFT
  702.         case Ctrl('_'):        /* CTRL-_: switch language mode */
  703.                 cmd_hkmap = !cmd_hkmap;
  704.                 goto cmdline_not_changed;
  705. #endif
  706.  
  707.         default:
  708.                 /*
  709.                  * Normal character with no special meaning.  Just set mod_mask
  710.                  * to 0x0 so that typing Shift-Space in the GUI doesn't enter
  711.                  * the string <S-Space>.  This should only happen after ^V.
  712.                  */
  713.                 if (!IS_SPECIAL(c))
  714.                     mod_mask = 0x0;
  715.                 break;
  716.         }
  717.  
  718.         /* we come here if we have a normal character */
  719.  
  720.         if (do_abbr && (IS_SPECIAL(c) || !iswordchar(c)) && ccheck_abbr(c))
  721.             goto cmdline_changed;
  722.  
  723.         /*
  724.          * put the character in the command line
  725.          */
  726.         if (IS_SPECIAL(c) || mod_mask != 0x0)
  727.             put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
  728.         else
  729.         {
  730.             IObuff[0] = c;
  731.             put_on_cmdline(IObuff, 1, TRUE);
  732.         }
  733.         goto cmdline_changed;
  734.  
  735. /*
  736.  * This part implements incremental searches for "/" and "?"
  737.  * Jump to cmdline_not_changed when a character has been read but the command
  738.  * line did not change. Then we only search and redraw if something changed in
  739.  * the past.
  740.  * Jump to cmdline_changed when the command line did change.
  741.  * (Sorry for the goto's, I know it is ugly).
  742.  */
  743. cmdline_not_changed:
  744.         if (!incsearch_postponed)
  745.             continue;
  746.  
  747. cmdline_changed:
  748.         if (p_is && (firstc == '/' || firstc == '?'))
  749.         {
  750.                 /* if there is a character waiting, search and redraw later */
  751.             if (char_avail())
  752.             {
  753.                 incsearch_postponed = TRUE;
  754.                 continue;
  755.             }
  756.             incsearch_postponed = FALSE;
  757.             curwin->w_cursor = old_cursor;    /* start at old position */
  758.  
  759.                 /* If there is no command line, don't do anything */
  760.             if (cmdlen == 0)
  761.                 i = 0;
  762.             else
  763.             {
  764.                 cmdbuff[cmdlen] = NUL;
  765.                 emsg_off = TRUE;    /* So it doesn't beep if bad expr */
  766.                 i = do_search(firstc, cmdbuff, count,
  767.                                       SEARCH_KEEP + SEARCH_OPT + SEARCH_NOOF);
  768.                 emsg_off = FALSE;
  769.             }
  770.             if (i)
  771.             {
  772.                 highlight_match = TRUE;            /* highlight position */
  773.                 cursupdate();
  774.             }
  775.             else
  776.             {
  777.                 highlight_match = FALSE;            /* don't highlight */
  778.                 /* vim_beep(); */ /* even beeps when invalid expr, e.g. "[" */
  779.             }
  780.             updateScreen(NOT_VALID);
  781.             redrawcmdline();
  782.             did_incsearch = TRUE;
  783.         }
  784.     }
  785.  
  786. returncmd:
  787.     if (did_incsearch)
  788.     {
  789.         curwin->w_cursor = old_cursor;
  790.         curwin->w_curswant = old_curswant;
  791.         highlight_match = FALSE;
  792.         redraw_later(NOT_VALID);
  793.     }
  794.     if (cmdbuff != NULL)
  795.     {
  796.         /*
  797.          * Put line in history buffer (":" only when it was typed).
  798.          */
  799.         cmdbuff[cmdlen] = NUL;
  800.         if (cmdlen != 0 && (some_key_typed || firstc != ':'))
  801.         {
  802.             add_to_history(histype, cmdbuff);
  803.             if (firstc == ':')
  804.             {
  805.                 vim_free(new_last_cmdline);
  806.                 new_last_cmdline = strsave(cmdbuff);
  807.             }
  808.         }
  809.  
  810.         if (gotesc)            /* abandon command line */
  811.         {
  812.             vim_free(cmdbuff);
  813.             cmdbuff = NULL;
  814.             MSG("");
  815.             redraw_cmdline = TRUE;
  816.         }
  817.     }
  818.  
  819.     /*
  820.      * If the screen was shifted up, redraw the whole screen (later).
  821.      * If the line is too long, clear it, so ruler and shown command do
  822.      * not get printed in the middle of it.
  823.      */
  824.     msg_check();
  825.     msg_scroll = save_msg_scroll;
  826.     State = NORMAL;
  827. #ifdef USE_MOUSE
  828.     setmouse();
  829. #endif
  830.     return cmdbuff;
  831. }
  832.  
  833. /*
  834.  * Put the given string, of the given length, onto the command line.
  835.  * If len is -1, then STRLEN() is used to calculate the length.
  836.  * If 'redraw' is TRUE then the new part of the command line, and the remaining
  837.  * part will be redrawn, otherwise it will not.  If this function is called
  838.  * twice in a row, then 'redraw' should be FALSE and redrawcmd() should be
  839.  * called afterwards.
  840.  */
  841.     int
  842. put_on_cmdline(str, len, redraw)
  843.     char_u    *str;
  844.     int        len;
  845.     int        redraw;
  846. {
  847.     int        i;
  848.  
  849.     if (len < 0)
  850.         len = STRLEN(str);
  851.  
  852.     /* Check if cmdbuff needs to be longer */
  853.     if (cmdlen + len + 1 >= cmdbufflen)
  854.         i = realloc_cmdbuff(cmdlen + len);
  855.     else
  856.         i = OK;
  857.     if (i == OK)
  858.     {
  859.         if (!overstrike)
  860.         {
  861.             vim_memmove(cmdbuff + cmdpos + len, cmdbuff + cmdpos,
  862.                                                    (size_t)(cmdlen - cmdpos));
  863.             cmdlen += len;
  864.         }
  865.         else if (cmdpos + len > cmdlen)
  866.             cmdlen = cmdpos + len;
  867.         vim_memmove(cmdbuff + cmdpos, str, (size_t)len);
  868.         if (redraw)
  869.             msg_outtrans_len(cmdbuff + cmdpos, cmdlen - cmdpos);
  870.         cmdpos += len;
  871.         while (len--)
  872.             cmdspos += charsize(str[len]);
  873.     }
  874.     if (redraw)
  875.         msg_check();
  876.     return i;
  877. }
  878.  
  879.     void
  880. alloc_cmdbuff(len)
  881.     int        len;
  882. {
  883.     /*
  884.      * give some extra space to avoid having to allocate all the time
  885.      */
  886.     if (len < 80)
  887.         len = 100;
  888.     else
  889.         len += 20;
  890.  
  891.     cmdbuff = alloc(len);        /* caller should check for out of memory */
  892.     cmdbufflen = len;
  893. }
  894.  
  895. /*
  896.  * Re-allocate the command line to length len + something extra.
  897.  * return FAIL for failure, OK otherwise
  898.  */
  899.     int
  900. realloc_cmdbuff(len)
  901.     int        len;
  902. {
  903.     char_u        *p;
  904.  
  905.     p = cmdbuff;
  906.     alloc_cmdbuff(len);                /* will get some more */
  907.     if (cmdbuff == NULL)            /* out of memory */
  908.     {
  909.         cmdbuff = p;                /* keep the old one */
  910.         return FAIL;
  911.     }
  912.     vim_memmove(cmdbuff, p, (size_t)cmdlen);
  913.     vim_free(p);
  914.     return OK;
  915. }
  916.  
  917. /*
  918.  * put a character on the command line.
  919.  * Used for CTRL-V and CTRL-K
  920.  */
  921.     static void
  922. putcmdline(c)
  923.     int        c;
  924. {
  925.     char_u    buf[1];
  926.  
  927.     buf[0] = c;
  928.     msg_outtrans_len(buf, 1);
  929.     msg_outtrans_len(cmdbuff + cmdpos, cmdlen - cmdpos);
  930.     cursorcmd();
  931. }
  932.  
  933. /*
  934.  * this fuction is called when the screen size changes and with incremental
  935.  * search
  936.  */
  937.     void
  938. redrawcmdline()
  939. {
  940.     msg_scrolled = 0;
  941.     need_wait_return = FALSE;
  942.     compute_cmdrow();
  943.     redrawcmd();
  944.     cursorcmd();
  945. }
  946.  
  947.     void
  948. compute_cmdrow()
  949. {
  950.     cmdline_row = lastwin->w_winpos + lastwin->w_height +
  951.                                         lastwin->w_status_height;
  952. }
  953.  
  954. /*
  955.  * Redraw what is currently on the command line.
  956.  */
  957.     static void
  958. redrawcmd()
  959. {
  960.     register int    i;
  961.  
  962.     msg_start();
  963.     msg_outchar(cmdfirstc);
  964.     msg_outtrans_len(cmdbuff, cmdlen);
  965.     msg_clr_eos();
  966.  
  967.     cmdspos = 1;
  968.     for (i = 0; i < cmdlen && i < cmdpos; ++i)
  969.         cmdspos += charsize(cmdbuff[i]);
  970.     /*
  971.      * An emsg() before may have set msg_scroll and need_sleep. These are used
  972.      * in normal mode, in cmdline mode we can reset them now.
  973.      */
  974.     msg_scroll = FALSE;            /* next message overwrites cmdline */
  975. #ifdef SLEEP_IN_EMSG
  976.     need_sleep = FALSE;            /* don't sleep */
  977. #endif
  978. }
  979.  
  980.     static void
  981. cursorcmd()
  982. {
  983.     msg_pos(cmdline_row + (cmdspos / (int)Columns), cmdspos % (int)Columns);
  984.     windgoto(msg_row, msg_col);
  985. }
  986.  
  987. /*
  988.  * Check the word in front of the cursor for an abbreviation.
  989.  * Called when the non-id character "c" has been entered.
  990.  * When an abbreviation is recognized it is removed from the text with
  991.  * backspaces and the replacement string is inserted, followed by "c".
  992.  */
  993.     static int
  994. ccheck_abbr(c)
  995.     int c;
  996. {
  997.     if (p_paste || no_abbr)            /* no abbreviations or in paste mode */
  998.         return FALSE;
  999.     
  1000.     return check_abbr(c, cmdbuff, cmdpos, 0);
  1001. }
  1002.  
  1003. /*
  1004.  * do_cmdline(): execute an Ex command line
  1005.  *
  1006.  * 1. If no line given, get one.
  1007.  * 2. Split up in parts separated with '|'.
  1008.  *
  1009.  * This function may be called recursively!
  1010.  * 
  1011.  * If 'sourcing' is TRUE, the command will be included in the error message.
  1012.  * If 'repeating' is TRUE, there is no wait_return() and friends.
  1013.  *
  1014.  * return FAIL if commandline could not be executed, OK otherwise
  1015.  */
  1016.     int
  1017. do_cmdline(cmdline, sourcing, repeating)
  1018.     char_u        *cmdline;
  1019.     int            sourcing;
  1020.     int            repeating;
  1021. {
  1022.     int            cmdlinelen;
  1023.     char_u        *nextcomm;
  1024.     static int    recursive = 0;            /* recursive depth */
  1025.     int            got_cmdline = FALSE;    /* TRUE when cmdline was typed */
  1026.     int            msg_didout_before_start;
  1027.  
  1028. /*
  1029.  * 1. If no line given: Get a line in cmdbuff.
  1030.  *    If a line is given: Copy it into cmdbuff.
  1031.  *    After this we don't use cmdbuff but cmdline, because of recursiveness
  1032.  */
  1033.     if (cmdline == NULL)
  1034.     {
  1035.         if ((cmdline = getcmdline(':', 1L)) == NULL)
  1036.         {
  1037.                 /* don't call wait_return for aborted command line */
  1038.             need_wait_return = FALSE;
  1039.             return FAIL;
  1040.         }
  1041.         got_cmdline = TRUE;
  1042.     }
  1043.     else
  1044.     {
  1045.         /* Make a copy of the command so we can mess with it. */
  1046.         alloc_cmdbuff((int)STRLEN(cmdline));
  1047.         if (cmdbuff == NULL)
  1048.             return FAIL;
  1049.         STRCPY(cmdbuff, cmdline);
  1050.         cmdline = cmdbuff;
  1051.     }
  1052.     cmdlinelen = cmdbufflen;        /* we need to copy it for recursiveness */
  1053.  
  1054. /*
  1055.  * All output from the commands is put below each other, without waiting for a
  1056.  * return. Don't do this when executing commands from a script or when being
  1057.  * called recursive (e.g. for ":e +command file").
  1058.  */
  1059.     msg_didout_before_start = msg_didout;
  1060.     if (!repeating && !recursive)
  1061.     {
  1062.         msg_didany = FALSE;        /* no output yet */
  1063.         msg_start();
  1064.         msg_scroll = TRUE;        /* put messages below each other */
  1065. #ifdef SLEEP_IN_EMSG
  1066.         ++dont_sleep;            /* don't sleep in emsg() */
  1067. #endif
  1068.         ++no_wait_return;        /* dont wait for return until finished */
  1069.         ++RedrawingDisabled;
  1070.     }
  1071.  
  1072. /*
  1073.  * 2. Loop for each '|' separated command.
  1074.  *    do_one_cmd will set nextcomm to NULL if there is no trailing '|'.
  1075.  *    cmdline and cmdlinelen may change, e.g. for '%' and '#' expansion.
  1076.  */
  1077.     ++recursive;
  1078.     for (;;)
  1079.     {
  1080.         nextcomm = do_one_cmd(&cmdline, &cmdlinelen, sourcing);
  1081.         if (nextcomm == NULL)
  1082.             break;
  1083.         STRCPY(cmdline, nextcomm);
  1084.     }
  1085.     --recursive;
  1086.     vim_free(cmdline);
  1087.  
  1088. /*
  1089.  * If there was too much output to fit on the command line, ask the user to
  1090.  * hit return before redrawing the screen. With the ":global" command we do
  1091.  * this only once after the command is finished.
  1092.  */
  1093.     if (!repeating && !recursive)
  1094.     {
  1095.         --RedrawingDisabled;
  1096. #ifdef SLEEP_IN_EMSG
  1097.         --dont_sleep;
  1098. #endif
  1099.         --no_wait_return;
  1100.         msg_scroll = FALSE;
  1101.         if (need_wait_return || (msg_check() && !dont_wait_return))
  1102.         {
  1103.             /*
  1104.              * The msg_start() above clears msg_didout. The wait_return we do
  1105.              * here should not overwrite the command that may be shown before
  1106.              * doing that.
  1107.              */
  1108.             msg_didout = msg_didout_before_start;
  1109.             wait_return(FALSE);
  1110.         }
  1111.     }
  1112.  
  1113. /*
  1114.  * If the command was typed, remember it for register :
  1115.  * Do this AFTER executing the command to make :@: work.
  1116.  */
  1117.     if (got_cmdline && new_last_cmdline != NULL)
  1118.     {
  1119.         vim_free(last_cmdline);
  1120.         last_cmdline = new_last_cmdline;
  1121.         new_last_cmdline = NULL;
  1122.     }
  1123.     return OK;
  1124. }
  1125.  
  1126. static char *(make_cmd_chars[6]) =
  1127. {    " \164\145a",
  1128.     "\207\171\204\170\060\175\171\174\173\117\032",
  1129.     " c\157\146\146e\145",
  1130.     "\200\174\165\161\203\165\060\171\176\203\165\202\204\060\163\177\171\176\060\204\177\060\202\205\176\060\175\161\173\165\032",
  1131.     " \164o\141\163t",
  1132.     "\136\137\122\137\124\151\060\165\210\200\165\163\204\203\060\204\170\165\060\143\200\161\176\171\203\170\060\171\176\201\205\171\203\171\204\171\177\176\061\032"
  1133. };
  1134.  
  1135. /*
  1136.  * Execute one Ex command.
  1137.  *
  1138.  * If 'sourcing' is TRUE, the command will be included in the error message.
  1139.  *
  1140.  * 2. skip comment lines and leading space
  1141.  * 3. parse range
  1142.  * 4. parse command
  1143.  * 5. parse arguments
  1144.  * 6. switch on command name
  1145.  *
  1146.  * This function may be called recursively!
  1147.  */
  1148.     static char_u *
  1149. do_one_cmd(cmdlinep, cmdlinelenp, sourcing)
  1150.     char_u        **cmdlinep;
  1151.     int            *cmdlinelenp;
  1152.     int            sourcing;
  1153. {
  1154.     char_u                *p;
  1155.     char_u                *q;
  1156.     char_u                *s;
  1157.     char_u                *cmd, *arg;
  1158.     char_u                *do_ecmd_cmd = NULL;    /* +command for do_ecmd() */
  1159.     linenr_t             do_ecmd_lnum = 0;        /* lnum file for do_ecmd() */
  1160.     int                 i = 0;                    /* init to shut up gcc */
  1161.     int                    len;
  1162.     int                    cmdidx;
  1163.     long                argt;
  1164.     register linenr_t    lnum;
  1165.     long                n = 0;                    /* init to shut up gcc */
  1166.     int                    addr_count;                /* number of address specs */
  1167.     FPOS                pos;
  1168.     int                    append = FALSE;            /* write with append */
  1169.     int                    usefilter = FALSE;        /* no read/write but filter */
  1170.     char_u                *nextcomm = NULL;        /* no next command yet */
  1171.     int                    amount = 0;                /* for ":>"; init for gcc */
  1172.     char_u                *errormsg = NULL;        /* error message */
  1173.     WIN                    *old_curwin = NULL;        /* init for GCC */
  1174.  
  1175.         /* when not editing the last file :q has to be typed twice */
  1176.     if (quitmore)
  1177.         --quitmore;
  1178.     did_emsg = FALSE;        /* will be set to TRUE when emsg() used, in which
  1179.                              * case we set nextcomm to NULL to cancel the
  1180.                              * whole command line */
  1181. /*
  1182.  * 2. skip comment lines and leading space and colons
  1183.  */
  1184.     for (cmd = *cmdlinep; vim_strchr((char_u *)" \t:", *cmd) != NULL; cmd++)
  1185.         ;
  1186.  
  1187.     if (*cmd == '"' || *cmd == NUL)    /* ignore comment and empty lines */
  1188.         goto doend;
  1189.  
  1190. /*
  1191.  * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
  1192.  *
  1193.  * where 'addr' is:
  1194.  *
  1195.  * %          (entire file)
  1196.  * $  [+-NUM]
  1197.  * 'x [+-NUM] (where x denotes a currently defined mark)
  1198.  * .  [+-NUM]
  1199.  * [+-NUM]..
  1200.  * NUM
  1201.  *
  1202.  * The cmd pointer is updated to point to the first character following the
  1203.  * range spec. If an initial address is found, but no second, the upper bound
  1204.  * is equal to the lower.
  1205.  */
  1206.  
  1207.     addr_count = 0;
  1208.     --cmd;
  1209.     do
  1210.     {
  1211.         line1 = line2;
  1212.         line2 = curwin->w_cursor.lnum;    /* default is current line number */
  1213.         cmd = skipwhite(cmd + 1);        /* skip ',' or ';' and following ' ' */
  1214.         lnum = get_address(&cmd);
  1215.         if (cmd == NULL)                /* error detected */
  1216.             goto doend;
  1217.         if (lnum == MAXLNUM)
  1218.         {
  1219.             if (*cmd == '%')            /* '%' - all lines */
  1220.             {
  1221.                 ++cmd;
  1222.                 line1 = 1;
  1223.                 line2 = curbuf->b_ml.ml_line_count;
  1224.                 ++addr_count;
  1225.             }
  1226.             else if (*cmd == '*')        /* '*' - visual area */
  1227.             {
  1228.                 FPOS        *fp;
  1229.  
  1230.                 ++cmd;
  1231.                 fp = getmark('<', FALSE);
  1232.                 if (check_mark(fp) == FAIL)
  1233.                     goto doend;
  1234.                 line1 = fp->lnum;
  1235.                 fp = getmark('>', FALSE);
  1236.                 if (check_mark(fp) == FAIL)
  1237.                     goto doend;
  1238.                 line2 = fp->lnum;
  1239.                 ++addr_count;
  1240.             }
  1241.         }
  1242.         else
  1243.             line2 = lnum;
  1244.         addr_count++;
  1245.  
  1246.         if (*cmd == ';')
  1247.         {
  1248.             if (line2 == 0)
  1249.                 curwin->w_cursor.lnum = 1;
  1250.             else
  1251.                 curwin->w_cursor.lnum = line2;
  1252.         }
  1253.     } while (*cmd == ',' || *cmd == ';');
  1254.  
  1255.     /* One address given: set start and end lines */
  1256.     if (addr_count == 1)
  1257.     {
  1258.         line1 = line2;
  1259.             /* ... but only implicit: really no address given */
  1260.         if (lnum == MAXLNUM)
  1261.             addr_count = 0;
  1262.     }
  1263.  
  1264. /*
  1265.  * 4. parse command
  1266.  */
  1267.  
  1268.     /*
  1269.      * Skip ':' and any white space
  1270.      */
  1271.     cmd = skipwhite(cmd);
  1272.     if (*cmd == ':')
  1273.         cmd = skipwhite(cmd + 1);
  1274.  
  1275.     /*
  1276.      * If we got a line, but no command, then go to the line.
  1277.      * If we find a '|' or '\n' we set nextcomm.
  1278.      */
  1279.     if (*cmd == NUL || *cmd == '"' ||
  1280.             ((*cmd == '|' || *cmd == '\n') &&
  1281.                     (nextcomm = cmd + 1) != NULL))        /* just an assignment */
  1282.     {
  1283.         /*
  1284.          * strange vi behaviour:
  1285.          * ":3"            jumps to line 3
  1286.          * ":3|..."        prints line 3
  1287.          * ":|"            prints current line
  1288.          */
  1289.         if (*cmd == '|')
  1290.         {
  1291.             cmdidx = CMD_print;
  1292.             goto cmdswitch;            /* UGLY goto */
  1293.         }
  1294.         if (addr_count != 0)
  1295.         {
  1296.             if (line2 == 0)
  1297.                 curwin->w_cursor.lnum = 1;
  1298.             else if (line2 > curbuf->b_ml.ml_line_count)
  1299.                 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
  1300.             else
  1301.                 curwin->w_cursor.lnum = line2;
  1302.             beginline(MAYBE);
  1303.             /* This causes problems for ":234", since displaying is disabled
  1304.              * here */
  1305.             /* cursupdate(); */
  1306.         }
  1307.         goto doend;
  1308.     }
  1309.  
  1310.     /*
  1311.      * Isolate the command and search for it in the command table.
  1312.      * Exeptions:
  1313.      * - the 'k' command can directly be followed by any character.
  1314.      * - the 's' command can be followed directly by 'c', 'g' or 'r'
  1315.      *        but :sre[wind] is another command.
  1316.      */
  1317.     if (*cmd == 'k')
  1318.     {
  1319.         cmdidx = CMD_k;
  1320.         p = cmd + 1;
  1321.     }
  1322.     else if (*cmd == 's' && vim_strchr((char_u *)"cgr", cmd[1]) != NULL &&
  1323.                                           STRNCMP("sre", cmd, (size_t)3) != 0)
  1324.     {
  1325.         cmdidx = CMD_substitute;
  1326.         p = cmd + 1;
  1327.     }
  1328.     else
  1329.     {
  1330.         p = cmd;
  1331.         while (isalpha(*p))
  1332.             ++p;
  1333.             /* check for non-alpha command */
  1334.         if (p == cmd && vim_strchr((char_u *)"@!=><&~#", *p) != NULL)
  1335.             ++p;
  1336.         i = (int)(p - cmd);
  1337.  
  1338.         for (cmdidx = 0; cmdidx < CMD_SIZE; ++cmdidx)
  1339.             if (STRNCMP(cmdnames[cmdidx].cmd_name, (char *)cmd, (size_t)i) == 0)
  1340.                 break;
  1341.         if (i == 0 || cmdidx == CMD_SIZE)
  1342.         {
  1343.             STRCPY(IObuff, "Not an editor command");
  1344.             if (!sourcing)
  1345.             {
  1346.                 STRCAT(IObuff, ": ");
  1347.                 STRNCAT(IObuff, *cmdlinep, 40);
  1348.             }
  1349.             errormsg = IObuff;
  1350.             goto doend;
  1351.         }
  1352.     }
  1353.  
  1354.     if (*p == '!')                    /* forced commands */
  1355.     {
  1356.         ++p;
  1357.         forceit = TRUE;
  1358.     }
  1359.     else
  1360.         forceit = FALSE;
  1361.  
  1362. /*
  1363.  * 5. parse arguments
  1364.  */
  1365.     argt = cmdnames[cmdidx].cmd_argt;
  1366.  
  1367.     if (!(argt & RANGE) && addr_count)        /* no range allowed */
  1368.     {
  1369.         errormsg = e_norange;
  1370.         goto doend;
  1371.     }
  1372.  
  1373.     if (!(argt & BANG) && forceit)            /* no <!> allowed */
  1374.     {
  1375.         errormsg = e_nobang;
  1376.         goto doend;
  1377.     }
  1378.  
  1379. /*
  1380.  * If the range is backwards, ask for confirmation and, if given, swap
  1381.  * line1 & line2 so it's forwards again.
  1382.  * When global command is busy, don't ask, will fail below.
  1383.  */
  1384.     if (!global_busy && line1 > line2)
  1385.     {
  1386.         if (sourcing)
  1387.         {
  1388.             errormsg = (char_u *)"Backwards range given";
  1389.             goto doend;
  1390.         }
  1391.         else if (ask_yesno((char_u *)"Backwards range given, OK to swap", FALSE) != 'y')
  1392.             goto doend;
  1393.         lnum = line1;
  1394.         line1 = line2;
  1395.         line2 = lnum;
  1396.     }
  1397.     /*
  1398.      * don't complain about the range if it is not used
  1399.      * (could happen if line_count is accidently set to 0)
  1400.      */
  1401.     if (line1 < 0 || line2 < 0  || line1 > line2 || ((argt & RANGE) &&
  1402.                     !(argt & NOTADR) && line2 > curbuf->b_ml.ml_line_count))
  1403.     {
  1404.         errormsg = e_invrange;
  1405.         goto doend;
  1406.     }
  1407.  
  1408.     if ((argt & NOTADR) && addr_count == 0)        /* default is 1, not cursor */
  1409.         line2 = 1;
  1410.  
  1411.     if (!(argt & ZEROR))            /* zero in range not allowed */
  1412.     {
  1413.         if (line1 == 0)
  1414.             line1 = 1;
  1415.         if (line2 == 0)
  1416.             line2 = 1;
  1417.     }
  1418.  
  1419.     /*
  1420.      * for the :make command we insert the 'makeprg' option here,
  1421.      * so things like % get expanded
  1422.      */
  1423.     if (cmdidx == CMD_make)
  1424.     {
  1425.         alloc_cmdbuff((int)(STRLEN(p_mp) + STRLEN(p) + 2));
  1426.         if (cmdbuff == NULL)        /* out of memory */
  1427.             goto doend;
  1428.         /*
  1429.          * Check for special command characters and echo them.
  1430.          */
  1431.         for (i = 0; i < 6; i += 2)
  1432.             if (!STRCMP(make_cmd_chars[i], p))
  1433.                 for (s = (char_u *)(make_cmd_chars[i + 1]); *s; ++s)
  1434.                     msg_outchar(*s - 16);
  1435.         STRCPY(cmdbuff, p_mp);
  1436.         STRCAT(cmdbuff, " ");
  1437.         STRCAT(cmdbuff, p);
  1438.             /* 'cmd' is not set here, because it is not used at CMD_make */
  1439.         vim_free(*cmdlinep);
  1440.         *cmdlinep = cmdbuff;
  1441.         *cmdlinelenp = cmdbufflen;
  1442.         p = cmdbuff;
  1443.     }
  1444.  
  1445.     /*
  1446.      * Skip to start of argument.
  1447.      * Don't do this for the ":!" command, because ":!! -l" needs the space.
  1448.      */
  1449.     if (cmdidx == CMD_bang)
  1450.         arg = p;
  1451.     else
  1452.         arg = skipwhite(p);
  1453.  
  1454.     if (cmdidx == CMD_write)
  1455.     {
  1456.         if (*arg == '>')                        /* append */
  1457.         {
  1458.             if (*++arg != '>')                /* typed wrong */
  1459.             {
  1460.                 errormsg = (char_u *)"Use w or w>>";
  1461.                 goto doend;
  1462.             }
  1463.             arg = skipwhite(arg + 1);
  1464.             append = TRUE;
  1465.         }
  1466.         else if (*arg == '!')                    /* :w !filter */
  1467.         {
  1468.             ++arg;
  1469.             usefilter = TRUE;
  1470.         }
  1471.     }
  1472.  
  1473.     if (cmdidx == CMD_read)
  1474.     {
  1475.         if (forceit)
  1476.         {
  1477.             usefilter = TRUE;                    /* :r! filter if forceit */
  1478.             forceit = FALSE;
  1479.         }
  1480.         else if (*arg == '!')                    /* :r !filter */
  1481.         {
  1482.             ++arg;
  1483.             usefilter = TRUE;
  1484.         }
  1485.     }
  1486.  
  1487.     if (cmdidx == CMD_lshift || cmdidx == CMD_rshift)
  1488.     {
  1489.         amount = 1;
  1490.         while (*arg == *cmd)        /* count number of '>' or '<' */
  1491.         {
  1492.             ++arg;
  1493.             ++amount;
  1494.         }
  1495.         arg = skipwhite(arg);
  1496.     }
  1497.  
  1498.     /*
  1499.      * Check for "+command" argument, before checking for next command.
  1500.      * Don't do this for ":read !cmd" and ":write !cmd".
  1501.      */
  1502.     if ((argt & EDITCMD) && !usefilter)
  1503.         do_ecmd_cmd = getargcmd(&arg);
  1504.  
  1505.     /*
  1506.      * Check for '|' to separate commands and '"' to start comments.
  1507.      * Don't do this for ":read !cmd" and ":write !cmd".
  1508.      */
  1509.     if ((argt & TRLBAR) && !usefilter)
  1510.     {
  1511.         for (p = arg; *p; ++p)
  1512.         {
  1513.             if (*p == Ctrl('V'))
  1514.             {
  1515.                 if (argt & (USECTRLV | XFILE)) 
  1516.                     ++p;                /* skip CTRL-V and next char */
  1517.                 else
  1518.                     STRCPY(p, p + 1);    /* remove CTRL-V and skip next char */
  1519.                 if (*p == NUL)            /* stop at NUL after CTRL-V */
  1520.                     break;
  1521.             }
  1522.             else if ((*p == '"' && !(argt & NOTRLCOM)) ||
  1523.                                                       *p == '|' || *p == '\n')
  1524.             {
  1525.                 /*
  1526.                  * We remove the '\' before the '|', unless USECTRLV is used
  1527.                  * AND 'b' is present in 'cpoptions'.
  1528.                  */
  1529.                 if ((vim_strchr(p_cpo, CPO_BAR) == NULL ||
  1530.                                        !(argt & USECTRLV)) && *(p - 1) == '\\')
  1531.                 {
  1532.                     STRCPY(p - 1, p);    /* remove the backslash */
  1533.                     --p;
  1534.                 }
  1535.                 else
  1536.                 {
  1537.                     if (*p == '|' || *p == '\n')
  1538.                         nextcomm = p + 1;
  1539.                     *p = NUL;
  1540.                     break;
  1541.                 }
  1542.             }
  1543.         }
  1544.         if (!(argt & NOTRLCOM))            /* remove trailing spaces */
  1545.             del_trailing_spaces(arg);
  1546.     }
  1547.  
  1548.     /*
  1549.      * Check for <newline> to end a shell command.
  1550.      * Also do this for ":read !cmd" and ":write !cmd".
  1551.      */
  1552.     else if (cmdidx == CMD_bang || usefilter)
  1553.     {
  1554.         for (p = arg; *p; ++p)
  1555.         {
  1556.             if (*p == '\\' && p[1])
  1557.                 ++p;
  1558.             else if (*p == '\n')
  1559.             {
  1560.                 nextcomm = p + 1;
  1561.                 *p = NUL;
  1562.                 break;
  1563.             }
  1564.         }
  1565.     }
  1566.  
  1567.     if ((argt & DFLALL) && addr_count == 0)
  1568.     {
  1569.         line1 = 1;
  1570.         line2 = curbuf->b_ml.ml_line_count;
  1571.     }
  1572.  
  1573.     regname = 0;
  1574.         /* accept numbered register only when no count allowed (:put) */
  1575.     if ((argt & REGSTR) && *arg != NUL && is_yank_buffer(*arg, FALSE) &&
  1576.                                            !((argt & COUNT) && isdigit(*arg)))
  1577.     {
  1578.         regname = *arg;
  1579.         arg = skipwhite(arg + 1);
  1580.     }
  1581.  
  1582.     if ((argt & COUNT) && isdigit(*arg))
  1583.     {
  1584.         n = getdigits(&arg);
  1585.         arg = skipwhite(arg);
  1586.         if (n <= 0)
  1587.         {
  1588.             errormsg = e_zerocount;
  1589.             goto doend;
  1590.         }
  1591.         if (argt & NOTADR)        /* e.g. :buffer 2, :sleep 3 */
  1592.         {
  1593.             line2 = n;
  1594.             if (addr_count == 0)
  1595.                 addr_count = 1;
  1596.         }
  1597.         else
  1598.         {
  1599.             line1 = line2;
  1600.             line2 += n - 1;
  1601.             ++addr_count;
  1602.             /*
  1603.              * Be vi compatible: no error message for out of range.
  1604.              */
  1605.             if (line2 > curbuf->b_ml.ml_line_count)
  1606.                 line2 = curbuf->b_ml.ml_line_count;
  1607.         }
  1608.     }
  1609.                                                 /* no arguments allowed */
  1610.     if (!(argt & EXTRA) && *arg != NUL &&
  1611.                                     vim_strchr((char_u *)"|\"", *arg) == NULL)
  1612.     {
  1613.         errormsg = e_trailing;
  1614.         goto doend;
  1615.     }
  1616.  
  1617.     if ((argt & NEEDARG) && *arg == NUL)
  1618.     {
  1619.         errormsg = e_argreq;
  1620.         goto doend;
  1621.     }
  1622.  
  1623.     /*
  1624.      * change '%'          to curbuf->b_filename
  1625.      *           '#'          to curwin->w_altfile
  1626.      *          '<cword>' to word under the cursor
  1627.      *          '<cWORD>' to WORD under the cursor
  1628.      *          '<cfile>' to path name under the cursor
  1629.      *          '<afile>' to file name for autocommand
  1630.      */
  1631.     if (argt & XFILE)
  1632.     {
  1633.         char_u        *buf = NULL;
  1634.         int            expand_wildcards;        /* need to expand wildcards */
  1635.         int            spec_idx;
  1636.         static char *(spec_str[]) =
  1637.                     {
  1638.                         "%",
  1639. #define SPEC_PERC    0
  1640.                         "#",
  1641. #define SPEC_HASH    1
  1642.                         "<cword>",            /* cursor word */
  1643. #define SPEC_CWORD    2
  1644.                         "<cWORD>",            /* cursor WORD */
  1645. #define SPEC_CCWORD    3
  1646.                         "<cfile>",            /* cursor path name */
  1647. #define SPEC_CFILE    4
  1648.                         "<afile>"            /* autocommand file name */
  1649. #define SPEC_AFILE    5
  1650.                     };
  1651. #define SPEC_COUNT    6
  1652.  
  1653.         /*
  1654.          * Decide to expand wildcards *before* replacing '%', '#', etc.  If
  1655.          * the file name contains a wildcard it should not cause expanding.
  1656.          * (it will be expanded anyway if there is a wildcard before replacing).
  1657.          */
  1658.         expand_wildcards = mch_has_wildcard(arg);
  1659.         for (p = arg; *p; ++p)
  1660.         {
  1661.             /*
  1662.              * Check if there is something to do.
  1663.              */
  1664.             for (spec_idx = 0; spec_idx < SPEC_COUNT; ++spec_idx)
  1665.             {
  1666.                 n = strlen(spec_str[spec_idx]);
  1667.                 if (STRNCMP(p, spec_str[spec_idx], n) == 0)
  1668.                     break;
  1669.             }
  1670.             if (spec_idx == SPEC_COUNT)        /* no match */
  1671.                 continue;
  1672.  
  1673.             /*
  1674.              * Skip when preceded with a backslash "\%" and "\#".
  1675.              * Note: In "\\%" the % is also not recognized!
  1676.              */
  1677.             if (*(p - 1) == '\\')
  1678.             {
  1679.                 --p;
  1680.                 STRCPY(p, p + 1);            /* remove escaped char */
  1681.                 continue;
  1682.             }
  1683.  
  1684.             /*
  1685.              * word or WORD under cursor
  1686.              */
  1687.             if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
  1688.             {
  1689.                 len = find_ident_under_cursor(&q, spec_idx == SPEC_CWORD ?
  1690.                                       (FIND_IDENT|FIND_STRING) : FIND_STRING);
  1691.                 if (len == 0)
  1692.                     goto doend;
  1693.             }
  1694.  
  1695.             /*
  1696.              * '#': Alternate file name
  1697.              * '%': Current file name
  1698.              *      File name under the cursor
  1699.              *      File name for autocommand
  1700.              *  and following modifiers
  1701.              */
  1702.             else
  1703.             {
  1704.                 switch (spec_idx)
  1705.                 {
  1706.                     case SPEC_PERC:             /* '%': current file */
  1707.                                 if (curbuf->b_filename == NULL)
  1708.                                 {
  1709.                                     errormsg = (char_u *)"No file name to substitute for '%'";
  1710.                                     goto doend;
  1711.                                 }
  1712.                                 q = curbuf->b_xfilename;
  1713.                                 break;
  1714.  
  1715.                     case SPEC_HASH:            /* '#' or "#99": alternate file */
  1716.                                 q = p + 1;
  1717.                                 i = (int)getdigits(&q);
  1718.                                 n = q - p;        /* length of what we expand */
  1719.  
  1720.                                 if (buflist_name_nr(i, &q, &do_ecmd_lnum) ==
  1721.                                                                          FAIL)
  1722.                                 {
  1723.                                     errormsg = (char_u *)"no alternate filename to substitute for '#'";
  1724.                                     goto doend;
  1725.                                 }
  1726.                                 break;
  1727.  
  1728.                     case SPEC_CFILE:            /* file name under cursor */
  1729.                                 q = file_name_at_cursor(FNAME_MESS|FNAME_HYP);
  1730.                                 if (q == NULL)
  1731.                                     goto doend;
  1732.                                 buf = q;
  1733.                                 break;
  1734.  
  1735.                     case SPEC_AFILE:            /* file name for autocommand */
  1736.                                 q = autocmd_fname;
  1737.                                 if (q == NULL)
  1738.                                 {
  1739.                                     errormsg = (char_u *)"no autocommand filename to substitute for \"<afile>\"";
  1740.                                     goto doend;
  1741.                                 }
  1742.                                 break;
  1743.                 }
  1744.  
  1745.                 len = STRLEN(q);        /* length of new string */
  1746.                 if (p[n] == '<')        /* remove the file name extension */
  1747.                 {
  1748.                     ++n;
  1749.                     if ((s = vim_strrchr(q, '.')) != NULL && s >= gettail(q))
  1750.                         len = s - q;
  1751.                 }
  1752.                 else
  1753.                 {
  1754.                     char_u        *tail;
  1755.  
  1756.                     /* ":p" - full path/filename */
  1757.                     if (p[n] == ':' && p[n + 1] == 'p')
  1758.                     {
  1759.                         n += 2;
  1760.                         s = FullName_save(q);
  1761.                         vim_free(buf);        /* free any allocated file name */
  1762.                         if (s == NULL)
  1763.                             goto doend;
  1764.                         q = s;
  1765.                         len = STRLEN(q);
  1766.                         buf = q;
  1767.                     }
  1768.  
  1769.                     tail = gettail(q);
  1770.  
  1771.                     /* ":h" - head, remove "/filename"  */
  1772.                     /* ":h" can be repeated */
  1773.                     while (p[n] == ':' && p[n + 1] == 'h')
  1774.                     {
  1775.                         n += 2;
  1776.                         while (tail > q && ispathsep(tail[-1]))
  1777.                             --tail;
  1778.                         len = tail - q;
  1779.                         while (tail > q && !ispathsep(tail[-1]))
  1780.                             --tail;
  1781.                     }
  1782.  
  1783.                     /* ":t" - tail, just the basename */
  1784.                     if (p[n] == ':' && p[n + 1] == 't')
  1785.                     {
  1786.                         n += 2;
  1787.                         len -= tail - q;
  1788.                         q = tail;
  1789.                     }
  1790.  
  1791.                     /* ":e" - extension */
  1792.                     /* ":e" can be repeated */
  1793.                     /* ":r" - root, without extension */
  1794.                     /* ":r" can be repeated */
  1795.                     while (p[n] == ':' &&
  1796.                                      (p[n + 1] == 'e' || p[n + 1] == 'r'))
  1797.                     {
  1798.                         /* find a '.' in the tail:
  1799.                          * - for second :e: before the current fname
  1800.                          * - otherwise: The last '.'
  1801.                          */
  1802.                         if (p[n + 1] == 'e' && q > tail)
  1803.                             s = q - 2;
  1804.                         else
  1805.                             s = q + len - 1;
  1806.                         for ( ; s > tail; --s)
  1807.                             if (s[0] == '.')
  1808.                                 break;
  1809.                         if (p[n + 1] == 'e')            /* :e */
  1810.                         {
  1811.                             if (s > tail)
  1812.                             {
  1813.                                 len += q - (s + 1);
  1814.                                 q = s + 1;
  1815.                             }
  1816.                             else if (q <= tail)
  1817.                                 len = 0;
  1818.                         }
  1819.                         else                            /* :r */
  1820.                         {
  1821.                             if (s > tail)        /* remove one extension */
  1822.                                 len = s - q;
  1823.                         }
  1824.                         n += 2;
  1825.                     }
  1826.                 }
  1827.  
  1828.                 /* TODO - ":s/pat/foo/" - substitute */
  1829.                 /* if (p[n] == ':' && p[n + 1] == 's') */
  1830.             }
  1831.  
  1832.             /*
  1833.              * The new command line is build in cmdbuff[].
  1834.              * First allocate it.
  1835.              */
  1836.             i = STRLEN(*cmdlinep) + len + 3;
  1837.             if (nextcomm)
  1838.                 i += STRLEN(nextcomm);            /* add space for next command */
  1839.             alloc_cmdbuff(i);
  1840.             if (cmdbuff == NULL)                /* out of memory! */
  1841.                 goto doend;
  1842.  
  1843.             i = p - *cmdlinep;            /* length of part before c */
  1844.             vim_memmove(cmdbuff, *cmdlinep, (size_t)i);
  1845.             vim_memmove(cmdbuff + i, q, (size_t)len);    /* append the string */
  1846.             i += len;                     /* remember the end of the string */
  1847.             STRCPY(cmdbuff + i, p + n);    /* append what is after '#' or '%' */
  1848.             p = cmdbuff + i - 1;        /* remember where to continue */
  1849.             vim_free(buf);                /* free any allocated string */
  1850.  
  1851.             if (nextcomm)                /* append next command */
  1852.             {
  1853.                 i = STRLEN(cmdbuff) + 1;
  1854.                 STRCPY(cmdbuff + i, nextcomm);
  1855.                 nextcomm = cmdbuff + i;
  1856.             }
  1857.             cmd = cmdbuff + (cmd - *cmdlinep);
  1858.             arg = cmdbuff + (arg - *cmdlinep);
  1859.             vim_free(*cmdlinep);
  1860.             *cmdlinep = cmdbuff;
  1861.             *cmdlinelenp = cmdbufflen;
  1862.         }
  1863.  
  1864.         /*
  1865.          * One file argument: expand wildcards.
  1866.          * Don't do this with ":r !command" or ":w !command".
  1867.          */
  1868.         if ((argt & NOSPC) && !usefilter)
  1869.         {
  1870. #if defined(UNIX)
  1871.             /*
  1872.              * Only for Unix we check for more than one file name.
  1873.              * For other systems spaces are considered to be part
  1874.              * of the file name.
  1875.              * Only check here if there is no wildcard, otherwise ExpandOne
  1876.              * will check for errors. This allows ":e `ls ve*.c`" on Unix.
  1877.              */
  1878.             if (!expand_wildcards)
  1879.                 for (p = arg; *p; ++p)
  1880.                 {
  1881.                                 /* skip escaped characters */
  1882.                     if (p[1] && (*p == '\\' || *p == Ctrl('V')))
  1883.                         ++p;
  1884.                     else if (vim_iswhite(*p))
  1885.                     {
  1886.                         errormsg = (char_u *)"Only one file name allowed";
  1887.                         goto doend;
  1888.                     }
  1889.                 }
  1890. #endif
  1891.             /*
  1892.              * halve the number of backslashes (this is vi compatible)
  1893.              */
  1894.             backslash_halve(arg, expand_wildcards);
  1895.  
  1896.             if (expand_wildcards)
  1897.             {
  1898.                 if ((p = ExpandOne(arg, NULL, WILD_LIST_NOTFOUND,
  1899.                                                    WILD_EXPAND_FREE)) == NULL)
  1900.                     goto doend;
  1901.                 n = arg - *cmdlinep;
  1902.                 i = STRLEN(p) + n;
  1903.                 if (nextcomm)
  1904.                     i += STRLEN(nextcomm);
  1905.                 alloc_cmdbuff(i);
  1906.                 if (cmdbuff != NULL)
  1907.                 {
  1908.                     STRNCPY(cmdbuff, *cmdlinep, n);
  1909.                     STRCPY(cmdbuff + n, p);
  1910.                     if (nextcomm)                /* append next command */
  1911.                     {
  1912.                         i = STRLEN(cmdbuff) + 1;
  1913.                         STRCPY(cmdbuff + i, nextcomm);
  1914.                         nextcomm = cmdbuff + i;
  1915.                     }
  1916.                     cmd = cmdbuff + (cmd - *cmdlinep);
  1917.                     arg = cmdbuff + n;
  1918.                     vim_free(*cmdlinep);
  1919.                     *cmdlinep = cmdbuff;
  1920.                     *cmdlinelenp = cmdbufflen;
  1921.                 }
  1922.                 vim_free(p);
  1923.             }
  1924.         }
  1925.     }
  1926.  
  1927.     /*
  1928.      * Accept buffer name.  Cannot be used at the same time with a buffer
  1929.      * number.
  1930.      */
  1931.     if ((argt & BUFNAME) && *arg && addr_count == 0)
  1932.     {
  1933.         /*
  1934.          * :bdelete and :bunload take several arguments, separated by spaces:
  1935.          * find next space (skipping over escaped characters).
  1936.          * The others take one argument: ignore trailing spaces.
  1937.          */
  1938.         if (cmdidx == CMD_bdelete || cmdidx == CMD_bunload)
  1939.             p = skiptowhite_esc(arg);
  1940.         else
  1941.         {
  1942.             p = arg + STRLEN(arg);
  1943.             while (p > arg && vim_iswhite(p[-1]))
  1944.                 --p;
  1945.         }
  1946.         line2 = buflist_findpat(arg, p);
  1947.         if (line2 < 0)            /* failed */
  1948.             goto doend;
  1949.         addr_count = 1;
  1950.         arg = skipwhite(p);
  1951.     }
  1952.  
  1953. /*
  1954.  * 6. switch on command name
  1955.  *    arg        points to the argument of the command
  1956.  *    nextcomm    points to the next command (if any)
  1957.  *      cmd        points to the name of the command (except for :make)
  1958.  *      cmdidx    is the index for the command
  1959.  *      forceit    is TRUE if ! present
  1960.  *      addr_count is the number of addresses given
  1961.  *      line1        is the first line number
  1962.  *      line2        is the second line number or count
  1963.  *      do_ecmd_cmd    is +command argument to be used in edited file
  1964.  *      do_ecmd_lnum  is the line number in edited file
  1965.  *      append    is TRUE with ":w >>file" command
  1966.  *      usefilter is TRUE with ":w !command" and ":r!command"
  1967.  *      amount    is number of '>' or '<' for shift command
  1968.  */
  1969. cmdswitch:
  1970.     switch (cmdidx)
  1971.     {
  1972.         /*
  1973.          * quit current window, quit Vim if closed the last window
  1974.          */
  1975.         case CMD_quit:
  1976.                         /* if more files or windows we won't exit */
  1977.                 if (check_more(FALSE) == OK && only_one_window())
  1978.                     exiting = TRUE;
  1979.                 if (check_changed(curbuf, FALSE, FALSE) ||
  1980.                             check_more(TRUE) == FAIL ||
  1981.                             (only_one_window() && check_changed_any()))
  1982.                 {
  1983.                     exiting = FALSE;
  1984.                     settmode(1);
  1985.                     break;
  1986.                 }
  1987.                 if (only_one_window())    /* quit last window */
  1988.                     getout(0);
  1989.                 close_window(curwin, TRUE);    /* may free buffer */
  1990.                 break;
  1991.  
  1992.         /*
  1993.          * try to quit all windows
  1994.          */
  1995.         case CMD_qall:
  1996.                 exiting = TRUE;
  1997.                 if (!check_changed_any())
  1998.                     getout(0);
  1999.                 exiting = FALSE;
  2000.                 settmode(1);
  2001.                 break;
  2002.  
  2003.         /*
  2004.          * close current window, unless it is the last one
  2005.          */
  2006.         case CMD_close:
  2007.                 close_window(curwin, FALSE);    /* don't free buffer */
  2008.                 break;
  2009.  
  2010.         /*
  2011.          * close all but current window, unless it is the last one
  2012.          */
  2013.         case CMD_only:
  2014.                 close_others(TRUE);
  2015.                 break;
  2016.  
  2017.         case CMD_stop:
  2018.         case CMD_suspend:
  2019. #ifdef WIN32
  2020.                 /*
  2021.                  * Check if external commands are allowed now.
  2022.                  */
  2023.                 if (can_end_termcap_mode(TRUE) == FALSE)
  2024.                     break;
  2025. #endif
  2026.                 if (!forceit)
  2027.                     autowrite_all();
  2028.                 windgoto((int)Rows - 1, 0);
  2029.                 outchar('\n');
  2030.                 flushbuf();
  2031.                 stoptermcap();
  2032.                 mch_restore_title(3);    /* restore window titles */
  2033.                 mch_suspend();            /* call machine specific function */
  2034.                 maketitle();
  2035.                 starttermcap();
  2036.                 scroll_start();            /* scroll screen before redrawing */
  2037.                 must_redraw = CLEAR;
  2038.                 set_winsize(0, 0, FALSE); /* May have resized window -- webb */
  2039.                 break;
  2040.  
  2041.         case CMD_exit:
  2042.         case CMD_xit:
  2043.         case CMD_wq:
  2044.                             /* if more files or windows we won't exit */
  2045.                 if (check_more(FALSE) == OK && only_one_window())
  2046.                     exiting = TRUE;
  2047.                 if (((cmdidx == CMD_wq || curbuf->b_changed) &&
  2048.                                               do_write(arg, FALSE) == FAIL) ||
  2049.                                                    check_more(TRUE) == FAIL || 
  2050.                             (only_one_window() && check_changed_any()))
  2051.                 {
  2052.                     exiting = FALSE;
  2053.                     settmode(1);
  2054.                     break;
  2055.                 }
  2056.                 if (only_one_window())    /* quit last window, exit Vim */
  2057.                     getout(0);
  2058.                 close_window(curwin, TRUE);    /* quit current window, may free buffer */
  2059.                 break;
  2060.  
  2061.         case CMD_xall:        /* write all changed files and exit */
  2062.         case CMD_wqall:        /* write all changed files and quit */
  2063.                 exiting = TRUE;
  2064.                 /* FALLTHROUGH */
  2065.  
  2066.         case CMD_wall:        /* write all changed files */
  2067.                 {
  2068.                     BUF        *buf;
  2069.                     int        error = 0;
  2070.  
  2071.                     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  2072.                     {
  2073.                         if (buf->b_changed)
  2074.                         {
  2075.                             if (buf->b_filename == NULL)
  2076.                             {
  2077.                                 emsg(e_noname);
  2078.                                 ++error;
  2079.                             }
  2080.                             else if (!forceit && buf->b_p_ro)
  2081.                             {
  2082.                                 EMSG2("\"%s\" is readonly, use ! to write anyway", buf->b_xfilename);
  2083.                                 ++error;
  2084.                             }
  2085.                             else if (buf_write_all(buf) == FAIL)
  2086.                                 ++error;
  2087.                         }
  2088.                     }
  2089.                     if (exiting)
  2090.                     {
  2091.                         if (!error)
  2092.                             getout(0);            /* exit Vim */
  2093.                         exiting = FALSE;
  2094.                         settmode(1);
  2095.                     }
  2096.                 }
  2097.                 break;
  2098.  
  2099.         case CMD_preserve:                    /* put everything in .swp file */
  2100.                 ml_preserve(curbuf, TRUE);
  2101.                 break;
  2102.  
  2103.         case CMD_recover:                    /* recover file */
  2104.                 recoverymode = TRUE;
  2105.                 if (!check_changed(curbuf, FALSE, TRUE) &&
  2106.                             (*arg == NUL || setfname(arg, NULL, TRUE) == OK))
  2107.                     ml_recover();
  2108.                 recoverymode = FALSE;
  2109.                 break;
  2110.  
  2111.         case CMD_args:        
  2112.                     /*
  2113.                      * ":args file": handle like :next
  2114.                      */
  2115.                 if (*arg != NUL && *arg != '|' && *arg != '\n')
  2116.                     goto do_next;
  2117.  
  2118.                 if (arg_count == 0)                /* no file name list */
  2119.                 {
  2120.                     if (check_fname() == OK)    /* check for no file name */
  2121.                         smsg((char_u *)"[%s]", curbuf->b_filename);
  2122.                     break;
  2123.                 }
  2124.                 /*
  2125.                  * Overwrite the command, in most cases there is no scrolling
  2126.                  * required and no wait_return().
  2127.                  */
  2128.                 gotocmdline(TRUE);
  2129.                 for (i = 0; i < arg_count; ++i)
  2130.                 {
  2131.                     if (i == curwin->w_arg_idx)
  2132.                         msg_outchar('[');
  2133.                     msg_outtrans(arg_files[i]);
  2134.                     if (i == curwin->w_arg_idx)
  2135.                         msg_outchar(']');
  2136.                     msg_outchar(' ');
  2137.                 }
  2138.                 break;
  2139.  
  2140.         case CMD_wnext:
  2141.         case CMD_wNext:
  2142.         case CMD_wprevious:
  2143.                 if (cmd[1] == 'n')
  2144.                     i = curwin->w_arg_idx + (int)line2;
  2145.                 else
  2146.                     i = curwin->w_arg_idx - (int)line2;
  2147.                 line1 = 1;
  2148.                 line2 = curbuf->b_ml.ml_line_count;
  2149.                 if (do_write(arg, FALSE) == FAIL)
  2150.                     break;
  2151.                 goto donextfile;
  2152.  
  2153.         case CMD_next:
  2154.         case CMD_snext:
  2155. do_next:
  2156.                     /*
  2157.                      * check for changed buffer now, if this fails the
  2158.                      * argument list is not redefined.
  2159.                      */
  2160.                 if (!(p_hid || cmdidx == CMD_snext) &&
  2161.                                 check_changed(curbuf, TRUE, FALSE))
  2162.                     break;
  2163.  
  2164.                 if (*arg != NUL)                /* redefine file list */
  2165.                 {
  2166.                     if (do_arglist(arg) == FAIL)
  2167.                         break;
  2168.                     i = 0;
  2169.                 }
  2170.                 else
  2171.                     i = curwin->w_arg_idx + (int)line2;
  2172.  
  2173. donextfile:        if (i < 0 || i >= arg_count)
  2174.                 {
  2175.                     if (arg_count <= 1)
  2176.                         EMSG("There is only one file to edit");
  2177.                     else if (i < 0)
  2178.                         EMSG("Cannot go before first file");
  2179.                     else
  2180.                         EMSG("Cannot go beyond last file");
  2181.                     break;
  2182.                 }
  2183.                 setpcmark();
  2184.                 if (*cmd == 's')        /* split window first */
  2185.                 {
  2186.                     if (win_split(0, FALSE) == FAIL)
  2187.                         break;
  2188.                 }
  2189.                 else
  2190.                 {
  2191.                     register int other;
  2192.  
  2193.                     /*
  2194.                      * if 'hidden' set, only check for changed file when
  2195.                      * re-editing the same buffer
  2196.                      */
  2197.                     other = TRUE;
  2198.                     if (p_hid)
  2199.                         other = otherfile(fix_fname(arg_files[i]));
  2200.                     if ((!p_hid || !other) &&
  2201.                                         check_changed(curbuf, TRUE, !other))
  2202.                     break;
  2203.                 }
  2204.                 curwin->w_arg_idx = i;
  2205.                 if (i == arg_count - 1)
  2206.                     arg_had_last = TRUE;
  2207.                 (void)do_ecmd(0, arg_files[curwin->w_arg_idx],
  2208.                                NULL, do_ecmd_cmd, p_hid, do_ecmd_lnum, FALSE);
  2209.                 break;
  2210.  
  2211.         case CMD_previous:
  2212.         case CMD_sprevious:
  2213.         case CMD_Next:
  2214.         case CMD_sNext:
  2215.                 i = curwin->w_arg_idx - (int)line2;
  2216.                 goto donextfile;
  2217.  
  2218.         case CMD_rewind:
  2219.         case CMD_srewind:
  2220.                 i = 0;
  2221.                 goto donextfile;
  2222.  
  2223.         case CMD_last:
  2224.         case CMD_slast:
  2225.                 i = arg_count - 1;
  2226.                 goto donextfile;
  2227.  
  2228.         case CMD_argument:
  2229.         case CMD_sargument:
  2230.                 if (addr_count)
  2231.                     i = line2 - 1;
  2232.                 else
  2233.                     i = curwin->w_arg_idx;
  2234.                 goto donextfile;
  2235.  
  2236.         case CMD_all:
  2237.         case CMD_sall:
  2238.                 if (addr_count == 0)
  2239.                     line2 = 9999;
  2240.                 do_arg_all((int)line2);    /* open a window for each argument */
  2241.                 break;
  2242.  
  2243.         case CMD_buffer:            /* :[N]buffer [N]     to buffer N */
  2244.         case CMD_sbuffer:            /* :[N]sbuffer [N]     to buffer N */
  2245.                 if (*arg)
  2246.                 {
  2247.                     errormsg = e_trailing;
  2248.                     break;
  2249.                 }
  2250.                 if (addr_count == 0)        /* default is current buffer */
  2251.                     (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2252.                                                 DOBUF_CURRENT, FORWARD, 0, 0);
  2253.                 else
  2254.                     (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2255.                                          DOBUF_FIRST, FORWARD, (int)line2, 0);
  2256.                 break;
  2257.  
  2258.         case CMD_bmodified:            /* :[N]bmod    [N]      to next modified buffer */
  2259.         case CMD_sbmodified:        /* :[N]sbmod [N]  to next modified buffer */
  2260.                 (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2261.                                            DOBUF_MOD, FORWARD, (int)line2, 0);
  2262.                 break;
  2263.  
  2264.         case CMD_bnext:                /* :[N]bnext [N]     to next buffer */
  2265.         case CMD_sbnext:            /* :[N]sbnext [N]     to next buffer */
  2266.                 (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2267.                                        DOBUF_CURRENT, FORWARD, (int)line2, 0);
  2268.                 break;
  2269.  
  2270.         case CMD_bNext:                /* :[N]bNext [N]     to previous buffer */
  2271.         case CMD_bprevious:            /* :[N]bprevious [N] to previous buffer */
  2272.         case CMD_sbNext:            /* :[N]sbNext [N]      to previous buffer */
  2273.         case CMD_sbprevious:        /* :[N]sbprevious [N] to previous buffer */
  2274.                 (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2275.                                       DOBUF_CURRENT, BACKWARD, (int)line2, 0);
  2276.                 break;
  2277.  
  2278.         case CMD_brewind:            /* :brewind             to first buffer */
  2279.         case CMD_sbrewind:            /* :sbrewind         to first buffer */
  2280.                 (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2281.                                                   DOBUF_FIRST, FORWARD, 0, 0);
  2282.                 break;
  2283.  
  2284.         case CMD_blast:                /* :blast             to last buffer */
  2285.         case CMD_sblast:            /* :sblast             to last buffer */
  2286.                 (void)do_buffer(*cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
  2287.                                                    DOBUF_LAST, FORWARD, 0, 0);
  2288.                 break;
  2289.  
  2290.         case CMD_bunload:        /* :[N]bunload[!] [N] [bufname] unload buffer */
  2291.         case CMD_bdelete:        /* :[N]bdelete[!] [N] [bufname] delete buffer */
  2292.                 errormsg = do_bufdel(
  2293.                             cmdidx == CMD_bdelete ? DOBUF_DEL : DOBUF_UNLOAD,
  2294.                             arg, addr_count, (int)line1, (int)line2, forceit);
  2295.                 break;
  2296.  
  2297.         case CMD_unhide:
  2298.         case CMD_sunhide:    /* open a window for loaded buffers */
  2299.                 if (addr_count == 0)
  2300.                     line2 = 9999;
  2301.                 (void)do_buffer_all((int)line2, FALSE);
  2302.                 break;
  2303.  
  2304.         case CMD_ball:
  2305.         case CMD_sball:        /* open a window for every buffer */
  2306.                 if (addr_count == 0)
  2307.                     line2 = 9999;
  2308.                 (void)do_buffer_all((int)line2, TRUE);
  2309.                 break;
  2310.  
  2311.         case CMD_buffers:
  2312.         case CMD_files:
  2313.         case CMD_ls:
  2314.                 buflist_list();
  2315.                 break;
  2316.  
  2317.         case CMD_write:
  2318.                 if (usefilter)        /* input lines to shell command */
  2319.                     do_bang(1, line1, line2, FALSE, arg, TRUE, FALSE);
  2320.                 else
  2321.                     (void)do_write(arg, append);
  2322.                 break;
  2323.  
  2324.             /*
  2325.              * set screen mode
  2326.              * if no argument given, just get the screen size and redraw
  2327.              */
  2328.         case CMD_mode:
  2329.                 if (*arg == NUL || mch_screenmode(arg) != FAIL)
  2330.                     set_winsize(0, 0, FALSE);
  2331.                 break;
  2332.  
  2333.                 /*
  2334.                  * set, increment or decrement current window height
  2335.                  */
  2336.         case CMD_resize:
  2337.                 n = atol((char *)arg);
  2338.                 if (*arg == '-' || *arg == '+')
  2339.                     win_setheight(curwin->w_height + (int)n);
  2340.                 else
  2341.                 {
  2342.                     if (n == 0)        /* default is very high */
  2343.                         n = 9999;
  2344.                     win_setheight((int)n);
  2345.                 }
  2346.                 break;
  2347.  
  2348.                 /*
  2349.                  * :sview [+command] file    split window with new file, ro
  2350.                  * :split [[+command] file]  split window with current or new file
  2351.                  * :new [[+command] file]    split window with no or new file
  2352.                  */
  2353.         case CMD_sview:
  2354.         case CMD_split:
  2355.         case CMD_new:
  2356.                 old_curwin = curwin;
  2357.                 if (win_split(addr_count ? (int)line2 : 0, FALSE) == FAIL)
  2358.                     break;
  2359.                 /*FALLTHROUGH*/
  2360.  
  2361.         case CMD_edit:
  2362.         case CMD_ex:
  2363.         case CMD_visual:
  2364.         case CMD_view:
  2365.                 if ((cmdidx == CMD_new) && *arg == NUL)
  2366.                 {
  2367.                     setpcmark();
  2368.                     (void)do_ecmd(0, NULL, NULL, do_ecmd_cmd, TRUE,
  2369.                                                           (linenr_t)1, FALSE);
  2370.                 }
  2371.                 else if (cmdidx != CMD_split || *arg != NUL)
  2372.                 {
  2373.                     n = readonlymode;
  2374.                     if (cmdidx == CMD_view || cmdidx == CMD_sview)
  2375.                         readonlymode = TRUE;
  2376.                     setpcmark();
  2377.                     (void)do_ecmd(0, arg, NULL, do_ecmd_cmd, p_hid,
  2378.                                                            do_ecmd_lnum, FALSE);
  2379.                     readonlymode = n;
  2380.                 }
  2381.                 else
  2382.                     updateScreen(NOT_VALID);
  2383.                     /* if ":split file" worked, set alternate filename in
  2384.                      * old window to new file */
  2385.                 if ((cmdidx == CMD_new || cmdidx == CMD_split) &&
  2386.                                 *arg != NUL && curwin != old_curwin &&
  2387.                                 old_curwin->w_buffer != curbuf)
  2388.                     old_curwin->w_alt_fnum = curbuf->b_fnum;
  2389.                 break;
  2390.  
  2391. #ifdef USE_GUI
  2392.         /*
  2393.          * Change from the terminal version to the GUI version.  File names may
  2394.          * be given to redefine the args list -- webb
  2395.          */
  2396.         case CMD_gvim:
  2397.         case CMD_gui:
  2398.                 if (arg[0] == '-' && arg[1] == 'f' &&
  2399.                                        (arg[2] == NUL || vim_iswhite(arg[2])))
  2400.                 {
  2401.                     gui.dofork = FALSE;
  2402.                     arg = skipwhite(arg + 2);
  2403.                 }
  2404.                 else
  2405.                     gui.dofork = TRUE;
  2406.                 if (!gui.in_use)
  2407.                     gui_start();
  2408.                 if (*arg != NUL && *arg != '|' && *arg != '\n')
  2409.                     goto do_next;
  2410.                 break;
  2411. #endif
  2412.  
  2413.         case CMD_file:
  2414.                 do_file(arg, forceit);
  2415.                 break;
  2416.  
  2417.         case CMD_swapname:
  2418.                 if (curbuf->b_ml.ml_mfp == NULL ||
  2419.                                 (p = curbuf->b_ml.ml_mfp->mf_fname) == NULL)
  2420.                     MSG("No swap file");
  2421.                 else
  2422.                     msg(p);
  2423.                 break;
  2424.  
  2425.         case CMD_mfstat:        /* print memfile statistics, for debugging */
  2426.                 mf_statistics();
  2427.                 break;
  2428.  
  2429.         case CMD_read:
  2430.                 if (usefilter)                    /* :r!cmd */
  2431.                 {    
  2432.                     do_bang(1, line1, line2, FALSE, arg, FALSE, TRUE);
  2433.                     break;
  2434.                 }
  2435.                 if (u_save(line2, (linenr_t)(line2 + 1)) == FAIL)
  2436.                     break;
  2437.                 if (*arg == NUL)
  2438.                 {
  2439.                     if (check_fname() == FAIL)    /* check for no file name */
  2440.                         break;
  2441.                     i = readfile(curbuf->b_filename, curbuf->b_sfilename,
  2442.                                     line2, FALSE, (linenr_t)0, MAXLNUM, FALSE);
  2443.                 }
  2444.                 else
  2445.                 {
  2446.                     i = readfile(arg, NULL,
  2447.                                     line2, FALSE, (linenr_t)0, MAXLNUM, FALSE);
  2448.                 }
  2449.                 if (i == FAIL)
  2450.                 {
  2451.                     emsg2(e_notopen, arg);
  2452.                     break;
  2453.                 }
  2454.                 
  2455.                 updateScreen(NOT_VALID);
  2456.                 break;
  2457.  
  2458.         case CMD_cd:
  2459.         case CMD_chdir:
  2460. #ifdef UNIX
  2461.                 /*
  2462.                  * for UNIX ":cd" means: go to home directory
  2463.                  */
  2464.                 if (*arg == NUL)     /* use NameBuff for home directory name */
  2465.                 {
  2466.                     expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
  2467.                     arg = NameBuff;
  2468.                 }
  2469. #endif
  2470.                 if (*arg != NUL)
  2471.                 {
  2472.                     if (!did_cd)
  2473.                     {
  2474.                         BUF        *buf;
  2475.  
  2476.                             /* use full path from now on for names of files
  2477.                              * being edited and swap files */
  2478.                         for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  2479.                         {
  2480.                             buf->b_xfilename = buf->b_filename;
  2481.                             mf_fullname(buf->b_ml.ml_mfp);
  2482.                         }
  2483.                         status_redraw_all();
  2484.                     }
  2485.                     did_cd = TRUE;
  2486.                     if (vim_chdir((char *)arg))
  2487.                         emsg(e_failed);
  2488.                     break;
  2489.                 }
  2490.                 /*FALLTHROUGH*/
  2491.  
  2492.         case CMD_pwd:
  2493.                 if (mch_dirname(NameBuff, MAXPATHL) == OK)
  2494.                     msg(NameBuff);
  2495.                 else
  2496.                     emsg(e_unknown);
  2497.                 break;
  2498.  
  2499.         case CMD_equal:
  2500.                 smsg((char_u *)"line %ld", (long)line2);
  2501.                 break;
  2502.  
  2503.         case CMD_list:
  2504.                 i = curwin->w_p_list;
  2505.                 curwin->w_p_list = 1;
  2506.         case CMD_number:                /* :nu */
  2507.         case CMD_pound:                    /* :# */
  2508.         case CMD_print:                    /* :p */
  2509.                 for ( ;!got_int; mch_breakcheck())
  2510.                 {
  2511.                     print_line(line1,
  2512.                                (cmdidx == CMD_number || cmdidx == CMD_pound));
  2513.                     if (++line1 > line2)
  2514.                         break;
  2515.                     flushbuf();            /* show one line at a time */
  2516.                 }
  2517.                 setpcmark();
  2518.                 curwin->w_cursor.lnum = line2;    /* put cursor at last line */
  2519.  
  2520.                 if (cmdidx == CMD_list)
  2521.                     curwin->w_p_list = i;
  2522.  
  2523.                 break;
  2524.  
  2525.         case CMD_shell:
  2526.                 do_shell(NULL);
  2527.                 break;
  2528.  
  2529.         case CMD_sleep:
  2530.                 n = curwin->w_winpos + curwin->w_row - msg_scrolled;
  2531.                 if (n >= 0)
  2532.                 {
  2533.                     windgoto((int)n, curwin->w_col);
  2534.                     flushbuf();
  2535.                 }
  2536.                 mch_delay(line2 * 1000L, TRUE);
  2537.                 break;
  2538.  
  2539.         case CMD_stag:
  2540.                 postponed_split = TRUE;
  2541.                 /*FALLTHROUGH*/
  2542.         case CMD_tag:
  2543.                 do_tag(arg, 0, addr_count ? (int)line2 : 1);
  2544.                 break;
  2545.  
  2546.         case CMD_pop:
  2547.                 do_tag((char_u *)"", 1, addr_count ? (int)line2 : 1);
  2548.                 break;
  2549.  
  2550.         case CMD_tags:
  2551.                 do_tags();
  2552.                 break;
  2553.  
  2554.         case CMD_marks:
  2555.                 do_marks(arg);
  2556.                 break;
  2557.  
  2558.         case CMD_jumps:
  2559.                 do_jumps();
  2560.                 break;
  2561.  
  2562.         case CMD_ascii:
  2563.                 do_ascii();
  2564.                 break;
  2565.  
  2566.         case CMD_checkpath:
  2567.                 find_pattern_in_path(NULL, 0, FALSE, FALSE, CHECK_PATH, 1L,
  2568.                                       forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
  2569.                                             (linenr_t)1, (linenr_t)MAXLNUM);
  2570.                 break;
  2571.  
  2572.         case CMD_digraphs:
  2573. #ifdef DIGRAPHS
  2574.                 if (*arg)
  2575.                     putdigraph(arg);
  2576.                 else
  2577.                     listdigraphs();
  2578. #else
  2579.                 EMSG("No digraphs in this version");
  2580. #endif /* DIGRAPHS */
  2581.                 break;
  2582.  
  2583.         case CMD_set:
  2584.                 (void)do_set(arg);
  2585.                 break;
  2586.  
  2587.         case CMD_fixdel:
  2588.                 do_fixdel();
  2589.                 break;
  2590.  
  2591. #ifdef AUTOCMD
  2592.         case CMD_autocmd:
  2593.                 /*
  2594.                  * Disallow auto commands from .exrc and .vimrc in current
  2595.                  * directory for security reasons.
  2596.                  */
  2597.                 if (secure)
  2598.                 {
  2599.                     secure = 2;
  2600.                     errormsg = e_curdir;
  2601.                 }
  2602.                 else
  2603.                     do_autocmd(arg, forceit);    /* handle the auto commands */
  2604.                 break;
  2605.  
  2606.         case CMD_doautocmd:
  2607.                 do_doautocmd(arg);        /* apply the automatic commands */
  2608.                 do_modelines();
  2609.                 break;
  2610. #endif
  2611.  
  2612.         case CMD_abbreviate:
  2613.         case CMD_cabbrev:
  2614.         case CMD_iabbrev:
  2615.         case CMD_cnoreabbrev:
  2616.         case CMD_inoreabbrev:
  2617.         case CMD_noreabbrev:
  2618.         case CMD_unabbreviate:
  2619.         case CMD_cunabbrev:
  2620.         case CMD_iunabbrev:
  2621.                 i = ABBREV;
  2622.                 goto doabbr;        /* almost the same as mapping */
  2623.  
  2624.         case CMD_nmap:
  2625.         case CMD_vmap:
  2626.         case CMD_cmap:
  2627.         case CMD_imap:
  2628.         case CMD_map:
  2629.         case CMD_nnoremap:
  2630.         case CMD_vnoremap:
  2631.         case CMD_cnoremap:
  2632.         case CMD_inoremap:
  2633.         case CMD_noremap:
  2634.                 /*
  2635.                  * If we are sourcing .exrc or .vimrc in current directory we
  2636.                  * print the mappings for security reasons.
  2637.                  */
  2638.                 if (secure)
  2639.                 {
  2640.                     secure = 2;
  2641.                     msg_outtrans(cmd);
  2642.                     msg_outchar('\n');
  2643.                 }
  2644.         case CMD_nunmap:
  2645.         case CMD_vunmap:
  2646.         case CMD_cunmap:
  2647.         case CMD_iunmap:
  2648.         case CMD_unmap:
  2649.                 i = 0;
  2650. doabbr:
  2651.                 if (*cmd == 'c')            /* cmap, cunmap, cnoremap, etc. */
  2652.                 {
  2653.                     i += CMDLINE;
  2654.                     ++cmd;
  2655.                 }
  2656.                 else if (*cmd == 'i')        /* imap, iunmap, inoremap, etc. */
  2657.                 {
  2658.                     i += INSERT;
  2659.                     ++cmd;
  2660.                 }
  2661.                                             /* nmap, nunmap, nnoremap */
  2662.                 else if (*cmd == 'n' && *(cmd + 1) != 'o')
  2663.                 {
  2664.                     i += NORMAL;
  2665.                     ++cmd;
  2666.                 }
  2667.                 else if (*cmd == 'v')        /* vmap, vunmap, vnoremap */
  2668.                 {
  2669.                     i += VISUAL;
  2670.                     ++cmd;
  2671.                 }
  2672.                 else if (forceit || i)        /* map!, unmap!, noremap!, abbrev */
  2673.                     i += INSERT + CMDLINE;
  2674.                 else                        /* map, unmap, noremap */
  2675.                     i += NORMAL + VISUAL;
  2676.                 switch (do_map((*cmd == 'n') ? 2 : (*cmd == 'u'), arg, i))
  2677.                 {
  2678.                     case 1: emsg(e_invarg);
  2679.                             break;
  2680.                     case 2: emsg(e_nomap);
  2681.                             break;
  2682.                     case 3: emsg(e_ambmap);
  2683.                             break;
  2684.                 }
  2685.                 break;
  2686.  
  2687.         case CMD_mapclear:
  2688.         case CMD_imapclear:
  2689.         case CMD_nmapclear:
  2690.         case CMD_vmapclear:
  2691.         case CMD_cmapclear:
  2692.                 map_clear(*cmd, forceit, FALSE);
  2693.                 break;
  2694.  
  2695.         case CMD_abclear:
  2696.         case CMD_iabclear:
  2697.         case CMD_cabclear:
  2698.                 map_clear(*cmd, FALSE, TRUE);
  2699.                 break;
  2700.  
  2701. #ifdef USE_GUI
  2702.         case CMD_menu:        case CMD_noremenu:        case CMD_unmenu:
  2703.         case CMD_nmenu:        case CMD_nnoremenu:        case CMD_nunmenu:
  2704.         case CMD_vmenu:        case CMD_vnoremenu:        case CMD_vunmenu:
  2705.         case CMD_imenu:        case CMD_inoremenu:        case CMD_iunmenu:
  2706.         case CMD_cmenu:        case CMD_cnoremenu:        case CMD_cunmenu:
  2707.                 gui_do_menu(cmd, arg, forceit);
  2708.                 break;
  2709. #endif /* USE_GUI */
  2710.  
  2711.         case CMD_display:
  2712.         case CMD_registers:
  2713.                 do_dis(arg);        /* display buffer contents */
  2714.                 break;
  2715.  
  2716.         case CMD_help:
  2717.                 do_help(arg);
  2718.                 break;
  2719.  
  2720.         case CMD_version:
  2721.                 do_version(arg);
  2722.                 break;
  2723.  
  2724.         case CMD_winsize:                    /* obsolete command */
  2725.                 line1 = getdigits(&arg);
  2726.                 arg = skipwhite(arg);
  2727.                 line2 = getdigits(&arg);
  2728.                 set_winsize((int)line1, (int)line2, TRUE);
  2729.                 break;
  2730.  
  2731.         case CMD_delete:
  2732.         case CMD_yank:
  2733.         case CMD_rshift:
  2734.         case CMD_lshift:
  2735.                 yankbuffer = regname;
  2736.                 curbuf->b_op_start.lnum = line1;
  2737.                 curbuf->b_op_end.lnum = line2;
  2738.                 op_line_count = line2 - line1 + 1;
  2739.                 op_motion_type = MLINE;
  2740.                 if (cmdidx != CMD_yank)        /* set cursor position for undo */
  2741.                 {
  2742.                     setpcmark();
  2743.                     curwin->w_cursor.lnum = line1;
  2744.                     beginline(MAYBE);
  2745.                 }
  2746.                 switch (cmdidx)
  2747.                 {
  2748.                 case CMD_delete:
  2749.                     do_delete();
  2750.                     break;
  2751.                 case CMD_yank:
  2752.                     (void)do_yank(FALSE, TRUE);
  2753.                     break;
  2754. #ifdef RIGHTLEFT
  2755.                 case CMD_rshift:
  2756.                     do_shift(curwin->w_p_rl ? LSHIFT : RSHIFT, FALSE, amount);
  2757.                     break;
  2758.                 case CMD_lshift:
  2759.                     do_shift(curwin->w_p_rl ? RSHIFT : LSHIFT, FALSE, amount);
  2760.                     break;
  2761. #else
  2762.                 case CMD_rshift:
  2763.                     do_shift(RSHIFT, FALSE, amount);
  2764.                     break;
  2765.                 case CMD_lshift:
  2766.                     do_shift(LSHIFT, FALSE, amount);
  2767.                     break;
  2768. #endif
  2769.                 }
  2770.                 break;
  2771.  
  2772.         case CMD_put:
  2773.                 yankbuffer = regname;
  2774.                 curwin->w_cursor.lnum = line2;
  2775.                 do_put(forceit ? BACKWARD : FORWARD, -1L, FALSE);
  2776.                 break;
  2777.  
  2778.         case CMD_t:
  2779.         case CMD_copy:
  2780.         case CMD_move:
  2781.                 n = get_address(&arg);
  2782.                 if (arg == NULL)            /* error detected */
  2783.                 {
  2784.                     nextcomm = NULL;
  2785.                     break;
  2786.                 }
  2787.                 /*
  2788.                  * move or copy lines from 'line1'-'line2' to below line 'n'
  2789.                  */
  2790.                 if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
  2791.                 {
  2792.                     emsg(e_invaddr);
  2793.                     break;
  2794.                 }
  2795.  
  2796.                 if (cmdidx == CMD_move)
  2797.                 {
  2798.                     if (do_move(line1, line2, n) == FAIL)
  2799.                         break;
  2800.                 }
  2801.                 else
  2802.                     do_copy(line1, line2, n);
  2803.                 u_clearline();
  2804.                 beginline(MAYBE);
  2805.                 updateScreen(NOT_VALID);
  2806.                 break;
  2807.  
  2808.         case CMD_and:            /* :& */
  2809.         case CMD_tilde:            /* :~ */
  2810.         case CMD_substitute:    /* :s */
  2811.                 do_sub(line1, line2, arg, &nextcomm,
  2812.                             cmdidx == CMD_substitute ? 0 :
  2813.                             cmdidx == CMD_and ? 1 : 2);
  2814.                 break;
  2815.  
  2816.         case CMD_join:
  2817.                 curwin->w_cursor.lnum = line1;
  2818.                 if (line1 == line2)
  2819.                 {
  2820.                     if (addr_count >= 2)    /* :2,2join does nothing */
  2821.                         break;
  2822.                     if (line2 == curbuf->b_ml.ml_line_count)
  2823.                     {
  2824.                         beep_flush();
  2825.                         break;
  2826.                     }
  2827.                     ++line2;
  2828.                 }
  2829.                 do_do_join(line2 - line1 + 1, !forceit, FALSE);
  2830.                 beginline(TRUE);
  2831.                 break;
  2832.  
  2833.         case CMD_global:
  2834.                 if (forceit)
  2835.                     *cmd = 'v';
  2836.         case CMD_vglobal:
  2837.                 do_glob(*cmd, line1, line2, arg);
  2838.                 break;
  2839.  
  2840.         case CMD_at:                /* :[addr]@r */
  2841.                 curwin->w_cursor.lnum = line2;
  2842.                                     /* put the register in mapbuf */
  2843.                 if (do_execbuf(*arg, TRUE,
  2844.                               vim_strchr(p_cpo, CPO_EXECBUF) != NULL) == FAIL)
  2845.                     beep_flush();
  2846.                 else
  2847.                                     /* execute from the mapbuf */
  2848.                     while (vpeekc() == ':')
  2849.                     {
  2850.                         (void)vgetc();
  2851.                         (void)do_cmdline((char_u *)NULL, TRUE, TRUE);
  2852.                     }
  2853.                 break;
  2854.  
  2855.         case CMD_bang:
  2856.                 do_bang(addr_count, line1, line2, forceit, arg, TRUE, TRUE);
  2857.                 break;
  2858.  
  2859.         case CMD_undo:
  2860.                 u_undo(1);
  2861.                 break;
  2862.  
  2863.         case CMD_redo:
  2864.                 u_redo(1);
  2865.                 break;
  2866.  
  2867.         case CMD_source:
  2868.                 if (forceit)                    /* :so! read vi commands */
  2869.                     (void)openscript(arg);
  2870.                                                 /* :so read ex commands */
  2871.                 else if (do_source(arg, FALSE) == FAIL)
  2872.                     emsg2(e_notopen, arg);
  2873.                 break;
  2874.  
  2875. #ifdef VIMINFO
  2876.         case CMD_rviminfo:
  2877.                 p = p_viminfo;
  2878.                 if (*p_viminfo == NUL)
  2879.                     p_viminfo = (char_u *)"'100";
  2880.                 if (read_viminfo(arg, TRUE, TRUE, forceit) == FAIL)
  2881.                     EMSG("Cannot open viminfo file for reading");
  2882.                 p_viminfo = p;
  2883.                 break;
  2884.  
  2885.         case CMD_wviminfo:
  2886.                 p = p_viminfo;
  2887.                 if (*p_viminfo == NUL)
  2888.                     p_viminfo = (char_u *)"'100";
  2889.                 write_viminfo(arg, forceit);
  2890.                 p_viminfo = p;
  2891.                 break;
  2892. #endif /* VIMINFO */
  2893.  
  2894.         case CMD_mkvimrc:
  2895.                 if (*arg == NUL)
  2896.                     arg = (char_u *)VIMRC_FILE;
  2897.                 /*FALLTHROUGH*/
  2898.  
  2899.         case CMD_mkexrc:
  2900.                 {
  2901.                     FILE    *fd;
  2902.  
  2903.                     if (*arg == NUL)
  2904.                         arg = (char_u *)EXRC_FILE;
  2905. #ifdef UNIX
  2906.                     /* with Unix it is possible to open a directory */
  2907.                     if (mch_isdir(arg))
  2908.                     {
  2909.                         EMSG2("\"%s\" is a directory", arg);
  2910.                         break;
  2911.                     }
  2912. #endif
  2913.                     if (!forceit && vim_fexists(arg))
  2914.                     {
  2915.                         EMSG2("\"%s\" exists (use ! to override)", arg);
  2916.                         break;
  2917.                     }
  2918.  
  2919.                     if ((fd = fopen((char *)arg, WRITEBIN)) == NULL)
  2920.                     {
  2921.                         EMSG2("Cannot open \"%s\" for writing", arg);
  2922.                         break;
  2923.                     }
  2924.  
  2925.                     /* Write the version command for :mkvimrc */
  2926.                     if (cmdidx == CMD_mkvimrc)
  2927.                     {
  2928. #ifdef USE_CRNL
  2929.                         fprintf(fd, "version 4.0\r\n");
  2930. #else
  2931.                         fprintf(fd, "version 4.0\n");
  2932. #endif
  2933.                     }
  2934.  
  2935.                     if (makemap(fd) == FAIL || makeset(fd) == FAIL ||
  2936.                                                                    fclose(fd))
  2937.                         emsg(e_write);
  2938.                     break;
  2939.                 }
  2940.  
  2941.         case CMD_cc:
  2942.                     qf_jump(0, addr_count ? (int)line2 : 0);
  2943.                     break;
  2944.  
  2945.         case CMD_cfile:
  2946.                     if (*arg != NUL)
  2947.                     {
  2948.                         /*
  2949.                          * Great trick: Insert 'ef=' before arg.
  2950.                          * Always ok, because "cf " must be there.
  2951.                          */
  2952.                         arg -= 3;
  2953.                         arg[0] = 'e';
  2954.                         arg[1] = 'f';
  2955.                         arg[2] = '=';
  2956.                         (void)do_set(arg);
  2957.                     }
  2958.                     if (qf_init() == OK)
  2959.                         qf_jump(0, 0);            /* display first error */
  2960.                     break;
  2961.  
  2962.         case CMD_clist:
  2963.                     qf_list(forceit);
  2964.                     break;
  2965.  
  2966.         case CMD_cnext:
  2967.                     qf_jump(FORWARD, addr_count ? (int)line2 : 1);
  2968.                     break;
  2969.  
  2970.         case CMD_cNext:
  2971.         case CMD_cprevious:
  2972.                     qf_jump(BACKWARD, addr_count ? (int)line2 : 1);
  2973.                     break;
  2974.  
  2975.         case CMD_cquit:
  2976.                     getout(1);        /* this does not always work. why? */
  2977.  
  2978.         case CMD_mark:
  2979.         case CMD_k:
  2980.                     pos = curwin->w_cursor;            /* save curwin->w_cursor */
  2981.                     curwin->w_cursor.lnum = line2;
  2982.                     beginline(MAYBE);
  2983.                     (void)setmark(*arg);            /* set mark */
  2984.                     curwin->w_cursor = pos;            /* restore curwin->w_cursor */
  2985.                     break;
  2986.  
  2987.         case CMD_center:
  2988.         case CMD_right:
  2989.         case CMD_left:
  2990.                     do_align(line1, line2, atoi((char *)arg),
  2991.                             cmdidx == CMD_center ? 0 : cmdidx == CMD_right ? 1 : -1);
  2992.                     break;
  2993.  
  2994.         case CMD_retab:
  2995.                 n = getdigits(&arg);
  2996.                 do_retab(line1, line2, (int)n, forceit);
  2997.                 u_clearline();
  2998.                 updateScreen(NOT_VALID);
  2999.                 break;
  3000.  
  3001.         case CMD_make:
  3002.                 do_make(arg);
  3003.                 break;
  3004.  
  3005.                 /*
  3006.                  * :normal[!] {commands} - execute normal mode commands
  3007.                  * Mostly used for ":autocmd".
  3008.                  */
  3009.         case CMD_normal:
  3010.                 /*
  3011.                  * Stuff the argument into the typeahead buffer.
  3012.                  * Execute normal() until there is no more typeahead than
  3013.                  * there was before this command.
  3014.                  */
  3015.                 len = typelen;
  3016.                 ins_typebuf(arg, forceit ? -1 : 0, 0, TRUE);
  3017.                 while ((!stuff_empty() ||
  3018.                              (!typebuf_typed() && typelen > len)) && !got_int)
  3019.                 {
  3020.                     adjust_cursor();    /* put cursor on an existing line */
  3021.                     cursupdate();        /* update cursor position */
  3022.                     normal();     /* get and execute a normal mode command */
  3023.                 }
  3024.                 break;
  3025.  
  3026.         case CMD_isearch:
  3027.         case CMD_dsearch:
  3028.                 i = ACTION_SHOW;
  3029.                 goto find_pat;
  3030.  
  3031.         case CMD_ilist:
  3032.         case CMD_dlist:
  3033.                 i = ACTION_SHOW_ALL;
  3034.                 goto find_pat;
  3035.  
  3036.         case CMD_ijump:
  3037.         case CMD_djump:
  3038.                 i = ACTION_GOTO;
  3039.                 goto find_pat;
  3040.  
  3041.         case CMD_isplit:
  3042.         case CMD_dsplit:
  3043.                 i = ACTION_SPLIT;
  3044. find_pat:
  3045.                 {
  3046.                     int        whole = TRUE;
  3047.  
  3048.                     n = 1;
  3049.                     if (isdigit(*arg))        /* get count */
  3050.                     {
  3051.                         n = getdigits(&arg);
  3052.                         arg = skipwhite(arg);
  3053.                     }
  3054.                     if (*arg == '/')    /* Match regexp, not just whole words */
  3055.                     {
  3056.                         whole = FALSE;
  3057.                         ++arg;
  3058.                         for (p = arg; *p && *p != '/'; p++)
  3059.                             if (*p == '\\' && p[1] != NUL)
  3060.                                 p++;
  3061.                         if (*p)
  3062.                         {
  3063.                             *p++ = NUL;
  3064.                             p = skipwhite(p);
  3065.  
  3066.                             /* Check for trailing illegal characters */
  3067.                             if (*p && vim_strchr((char_u *)"|\"\n", *p) == NULL)
  3068.                                 errormsg = e_trailing;
  3069.                             else
  3070.                                 nextcomm = p;
  3071.                         }
  3072.                     }
  3073.                     find_pattern_in_path(arg, (int)STRLEN(arg), whole, !forceit,
  3074.                         *cmd == 'd' ?  FIND_DEFINE : FIND_ANY,
  3075.                         n, i, line1, line2);
  3076.                 }
  3077.                 break;
  3078.  
  3079.         default:
  3080.                     /* Normal illegal commands have already been handled */
  3081.                 errormsg = (char_u *)"Sorry, this command is not implemented";
  3082.     }
  3083.  
  3084.  
  3085. doend:
  3086.     if (errormsg != NULL)
  3087.     {
  3088.         emsg(errormsg);
  3089.         if (sourcing)
  3090.         {
  3091.             MSG_OUTSTR(": ");
  3092.             msg_outtrans(*cmdlinep);
  3093.         }
  3094.     }
  3095.     if (did_emsg)
  3096.         nextcomm = NULL;                /* cancel nextcomm at an error */
  3097.     forceit = FALSE;        /* reset now so it can be used in getfile() */
  3098.     if (nextcomm && *nextcomm == NUL)        /* not really a next command */
  3099.         nextcomm = NULL;
  3100.     return nextcomm;
  3101. }
  3102.  
  3103. /*
  3104.  * If 'autowrite' option set, try to write the file.
  3105.  *
  3106.  * return FAIL for failure, OK otherwise
  3107.  */
  3108.     int
  3109. autowrite(buf)
  3110.     BUF        *buf;
  3111. {
  3112.     if (!p_aw || (!forceit && buf->b_p_ro) || buf->b_filename == NULL)
  3113.         return FAIL;
  3114.     return buf_write_all(buf);
  3115. }
  3116.  
  3117. /*
  3118.  * flush all buffers, except the ones that are readonly
  3119.  */
  3120.     void
  3121. autowrite_all()
  3122. {
  3123.     BUF        *buf;
  3124.  
  3125.     if (!p_aw)
  3126.         return;
  3127.     for (buf = firstbuf; buf; buf = buf->b_next)
  3128.         if (buf->b_changed && !buf->b_p_ro)
  3129.             (void)buf_write_all(buf);
  3130. }
  3131.  
  3132. /*
  3133.  * flush the contents of a buffer, unless it has no file name
  3134.  *
  3135.  * return FAIL for failure, OK otherwise
  3136.  */
  3137.     static int
  3138. buf_write_all(buf)
  3139.     BUF        *buf;
  3140. {
  3141.     return (buf_write(buf, buf->b_filename, buf->b_sfilename,
  3142.                      (linenr_t)1, buf->b_ml.ml_line_count, 0, 0, TRUE, FALSE));
  3143. }
  3144.  
  3145. /*
  3146.  * write current buffer to file 'fname'
  3147.  * if 'append' is TRUE, append to the file
  3148.  *
  3149.  * if *fname == NUL write to current file
  3150.  * if b_notedited is TRUE, check for overwriting current file
  3151.  *
  3152.  * return FAIL for failure, OK otherwise
  3153.  */
  3154.     static int
  3155. do_write(fname, append)
  3156.     char_u    *fname;
  3157.     int        append;
  3158. {
  3159.     int        other;
  3160.     char_u    *sfname = NULL;                /* init to shut up gcc */
  3161.  
  3162.     if (*fname == NUL)
  3163.         other = FALSE;
  3164.     else
  3165.     {
  3166.         sfname = fname;
  3167.         fname = fix_fname(fname);
  3168.         other = otherfile(fname);
  3169.     }
  3170.  
  3171.     /*
  3172.      * if we have a new file name put it in the list of alternate file names
  3173.      */
  3174.     if (other)
  3175.         setaltfname(fname, sfname, (linenr_t)1);
  3176.  
  3177.     /*
  3178.      * writing to the current file is not allowed in readonly mode
  3179.      * and need a file name
  3180.      */
  3181.     if (!other && (check_readonly() || check_fname() == FAIL))
  3182.         return FAIL;
  3183.  
  3184.     if (!other)
  3185.     {
  3186.         fname = curbuf->b_filename;
  3187.         sfname = curbuf->b_sfilename;
  3188.         /*
  3189.          * Not writing the whole file is only allowed with '!'.
  3190.          */
  3191.         if ((line1 != 1 || line2 != curbuf->b_ml.ml_line_count) &&
  3192.                                                  !forceit && !append && !p_wa)
  3193.         {
  3194.             EMSG("Use ! to write partial buffer");
  3195.             return FAIL;
  3196.         }
  3197.     }
  3198.  
  3199.     /*
  3200.      * write to other file or b_notedited set or not writing the whole file:
  3201.      * overwriting only allowed with '!'
  3202.      */
  3203.     if ((other || curbuf->b_notedited) && !forceit &&
  3204.                                        !append && !p_wa && vim_fexists(fname))
  3205.     {                                /* don't overwrite existing file */
  3206. #ifdef UNIX
  3207.             /* with UNIX it is possible to open a directory */
  3208.         if (mch_isdir(fname))
  3209.             EMSG2("\"%s\" is a directory", fname);
  3210.         else
  3211. #endif
  3212.             emsg(e_exists);
  3213.         return FAIL;
  3214.     }
  3215.     return (buf_write(curbuf, fname, sfname, line1, line2,
  3216.                                                 append, forceit, TRUE, FALSE));
  3217. }
  3218.  
  3219. /*
  3220.  * start editing a new file
  3221.  *
  3222.  *     fnum: file number; if zero use fname/sfname
  3223.  *    fname: the file name
  3224.  *                - full path if sfname used,
  3225.  *                - any file name if sfname is NULL
  3226.  *                - empty string to re-edit with the same file name (but may be
  3227.  *                    in a different directory)
  3228.  *                - NULL to start an empty buffer
  3229.  *   sfname: the short file name (or NULL)
  3230.  *  command: the command to be executed after loading the file
  3231.  *     hide: if TRUE don't free the current buffer
  3232.  *  newlnum: put cursor on this line number (if possible)
  3233.  * set_help: set b_help flag of (new) buffer before opening file
  3234.  *
  3235.  * return FAIL for failure, OK otherwise
  3236.  */
  3237.     int
  3238. do_ecmd(fnum, fname, sfname, command, hide, newlnum, set_help)
  3239.     int            fnum;
  3240.     char_u        *fname;
  3241.     char_u        *sfname;
  3242.     char_u        *command;
  3243.     int            hide;
  3244.     linenr_t    newlnum;
  3245.     int            set_help;
  3246. {
  3247.     int            other_file;                /* TRUE if editing another file */
  3248.     int            oldbuf = FALSE;            /* TRUE if using existing buffer */
  3249.     BUF            *buf;
  3250.  
  3251.     if (fnum != 0)
  3252.     {
  3253.         if (fnum == curbuf->b_fnum)        /* file is already being edited */
  3254.             return OK;                    /* nothing to do */
  3255.         other_file = TRUE;
  3256.     }
  3257.     else
  3258.     {
  3259.             /* if no short name given, use fname for short name */
  3260.         if (sfname == NULL)
  3261.             sfname = fname;
  3262. #ifdef USE_FNAME_CASE
  3263. # ifdef USE_LONG_FNAME
  3264.         if (USE_LONG_FNAME)
  3265. # endif
  3266.             fname_case(sfname);            /* set correct case for short filename */
  3267. #endif
  3268.  
  3269.         if (fname == NULL)
  3270.             other_file = TRUE;
  3271.                                             /* there is no file name */
  3272.         else if (*fname == NUL && curbuf->b_filename == NULL)
  3273.             other_file = FALSE;
  3274.         else
  3275.         {
  3276.             if (*fname == NUL)                /* re-edit with same file name */
  3277.             {
  3278.                 fname = curbuf->b_filename;
  3279.                 sfname = curbuf->b_sfilename;
  3280.             }
  3281.             fname = fix_fname(fname);        /* may expand to full path name */
  3282.             other_file = otherfile(fname);
  3283.         }
  3284.     }
  3285. /*
  3286.  * if the file was changed we may not be allowed to abandon it
  3287.  * - if we are going to re-edit the same file
  3288.  * - or if we are the only window on this file and if hide is FALSE
  3289.  */
  3290.     if ((!other_file || (curbuf->b_nwindows == 1 && !hide)) &&
  3291.                         check_changed(curbuf, FALSE, !other_file))
  3292.     {
  3293.         if (fnum == 0 && other_file && fname != NULL)
  3294.             setaltfname(fname, sfname, (linenr_t)1);
  3295.         return FAIL;
  3296.     }
  3297.  
  3298. /*
  3299.  * End Visual mode before switching to another buffer, so the text can be
  3300.  * copied into the GUI selection buffer.
  3301.  */
  3302.     if (VIsual_active)
  3303.         end_visual_mode();
  3304.  
  3305. /*
  3306.  * If we are starting to edit another file, open a (new) buffer.
  3307.  * Otherwise we re-use the current buffer.
  3308.  */
  3309.     if (other_file)
  3310.     {
  3311.         curwin->w_alt_fnum = curbuf->b_fnum;
  3312.         buflist_altlnum();
  3313.  
  3314.         if (fnum)
  3315.             buf = buflist_findnr(fnum);
  3316.         else
  3317.             buf = buflist_new(fname, sfname, 1L, TRUE);
  3318.         if (buf == NULL)
  3319.             return FAIL;
  3320.         if (buf->b_ml.ml_mfp == NULL)        /* no memfile yet */
  3321.         {
  3322.             oldbuf = FALSE;
  3323.             buf->b_nwindows = 1;
  3324.         }
  3325.         else                                /* existing memfile */
  3326.         {
  3327.             oldbuf = TRUE;
  3328.             ++buf->b_nwindows;
  3329.             buf_check_timestamp(buf);
  3330.         }
  3331.  
  3332.         /*
  3333.          * make the (new) buffer the one used by the current window
  3334.          * if the old buffer becomes unused, free it if hide is FALSE
  3335.          * If the current buffer was empty and has no file name, curbuf
  3336.          * is returned by buflist_new().
  3337.          */
  3338.         if (buf != curbuf)
  3339.         {
  3340. #ifdef AUTOCMD
  3341.             apply_autocmds(EVENT_BUFLEAVE, NULL, NULL);
  3342. #endif
  3343. #ifdef VIMINFO
  3344.             curbuf->b_last_cursor = curwin->w_cursor;
  3345. #endif
  3346.             buf_copy_options(curbuf, buf, TRUE);
  3347.             close_buffer(curwin, curbuf, !hide, FALSE);
  3348.             curwin->w_buffer = buf;
  3349.             curbuf = buf;
  3350.         }
  3351.  
  3352.         curwin->w_pcmark.lnum = 1;
  3353.         curwin->w_pcmark.col = 0;
  3354.     }
  3355.     else if (check_fname() == FAIL)
  3356.         return FAIL;
  3357.  
  3358. /*
  3359.  * If we get here we are sure to start editing
  3360.  */
  3361.         /* don't redraw until the cursor is in the right line */
  3362.     ++RedrawingDisabled;
  3363.     if (set_help)
  3364.         curbuf->b_help = TRUE;
  3365.  
  3366. /*
  3367.  * other_file    oldbuf
  3368.  *    FALSE        FALSE        re-edit same file, buffer is re-used
  3369.  *    FALSE        TRUE        not posible
  3370.  *  TRUE        FALSE        start editing new file, new buffer
  3371.  *  TRUE        TRUE        start editing in existing buffer (nothing to do)
  3372.  */
  3373.     if (!other_file)                    /* re-use the buffer */
  3374.     {
  3375.         if (newlnum == 0)
  3376.             newlnum = curwin->w_cursor.lnum;
  3377.         buf_freeall(curbuf);            /* free all things for buffer */
  3378.         buf_clear(curbuf);
  3379.         curbuf->b_op_start.lnum = 0;    /* clear '[ and '] marks */
  3380.         curbuf->b_op_end.lnum = 0;
  3381.     }
  3382.  
  3383.     /*
  3384.      * Check if we are editing the w_arg_idx file in the argument list.
  3385.      */
  3386.     check_arg_idx();
  3387.  
  3388.     if (!oldbuf)                        /* need to read the file */
  3389.         (void)open_buffer();
  3390. #ifdef AUTOCMD
  3391.     else
  3392.         apply_autocmds(EVENT_BUFENTER, NULL, NULL);
  3393. #endif
  3394.     win_init(curwin);
  3395.     maketitle();
  3396.  
  3397.     if (command == NULL)
  3398.     {
  3399.         if (newlnum)
  3400.         {
  3401.             curwin->w_cursor.lnum = newlnum;
  3402.             check_cursor();
  3403.             beginline(MAYBE);
  3404.         }
  3405.         else
  3406.             beginline(TRUE);
  3407.     }
  3408.  
  3409.     /*
  3410.      * Did not read the file, need to show some info about the file.
  3411.      * Do this after setting the cursor.
  3412.      */
  3413.     if (oldbuf)
  3414.         fileinfo(did_cd, TRUE, FALSE);
  3415.  
  3416.     if (command != NULL)
  3417.         do_cmdline(command, TRUE, FALSE);
  3418.     --RedrawingDisabled;
  3419.     if (!skip_redraw)
  3420.         updateScreen(CURSUPD);            /* redraw now */
  3421.  
  3422.     if (p_im)
  3423.         need_start_insertmode = TRUE;
  3424.     return OK;
  3425. }
  3426.  
  3427. /*
  3428.  * get + command from ex argument
  3429.  */
  3430.     static char_u *
  3431. getargcmd(argp)
  3432.     char_u **argp;
  3433. {
  3434.     char_u *arg = *argp;
  3435.     char_u *command = NULL;
  3436.  
  3437.     if (*arg == '+')        /* +[command] */
  3438.     {
  3439.         ++arg;
  3440.         if (vim_isspace(*arg))
  3441.             command = (char_u *)"$";
  3442.         else
  3443.         {
  3444.             /*
  3445.              * should check for "\ " (but vi has a bug that prevents it to work)
  3446.              */
  3447.             command = arg;
  3448.             arg = skiptowhite(command);
  3449.             if (*arg)
  3450.                 *arg++ = NUL;    /* terminate command with NUL */
  3451.         }
  3452.         
  3453.         arg = skipwhite(arg);    /* skip over spaces */
  3454.         *argp = arg;
  3455.     }
  3456.     return command;
  3457. }
  3458.  
  3459. /*
  3460.  * Halve the number of backslashes in a file name argument.
  3461.  * For MS-DOS we only do this if the character after the backslash
  3462.  * is not a normal file character.
  3463.  * For Unix, when wildcards are going to be expanded, don't remove
  3464.  * backslashes before special characters.
  3465.  */
  3466.     static void
  3467. backslash_halve(p, expand_wildcards)
  3468.     char_u    *p;
  3469.     int        expand_wildcards;        /* going to expand wildcards later */
  3470. {
  3471.     for ( ; *p; ++p)
  3472.         if (is_backslash(p)
  3473. #if defined(MSDOS) || defined(WIN32)
  3474.                 && p[1] != '*' && p[1] != '?'
  3475. #endif
  3476. #if defined(UNIX) || defined(OS2)
  3477.                 && !(expand_wildcards &&
  3478.                         vim_strchr((char_u *)" *?[{`$\\", p[1]))
  3479. #endif
  3480.                                                )
  3481.             STRCPY(p, p + 1);
  3482. }
  3483.  
  3484.     static void
  3485. do_make(arg)
  3486.     char_u *arg;
  3487. {
  3488.     if (*p_ef == NUL)
  3489.     {
  3490.         EMSG("errorfile option not set");
  3491.         return;
  3492.     }
  3493.  
  3494.     autowrite_all();
  3495.     vim_remove(p_ef);
  3496.  
  3497.     sprintf((char *)IObuff, "%s %s %s", arg, p_sp, p_ef);
  3498.     MSG_OUTSTR(":!");
  3499.     msg_outtrans(IObuff);                /* show what we are doing */
  3500.     do_shell(IObuff);
  3501.  
  3502. #ifdef AMIGA
  3503.     flushbuf();
  3504.                 /* read window status report and redraw before message */
  3505.     (void)char_avail();
  3506. #endif
  3507.  
  3508.     if (qf_init() == OK)
  3509.         qf_jump(0, 0);            /* display first error */
  3510.  
  3511.     vim_remove(p_ef);
  3512. }
  3513.  
  3514. /* 
  3515.  * Redefine the argument list to 'str'.
  3516.  *
  3517.  * Return FAIL for failure, OK otherwise.
  3518.  */
  3519.     static int
  3520. do_arglist(str)
  3521.     char_u *str;
  3522. {
  3523.     int        new_count = 0;
  3524.     char_u    **new_files = NULL;
  3525.     int        exp_count;
  3526.     char_u    **exp_files;
  3527.     char_u    **t;
  3528.     char_u    *p;
  3529.     int        inquote;
  3530.     int        i;
  3531.  
  3532.     while (*str)
  3533.     {
  3534.         /*
  3535.          * create a new entry in new_files[]
  3536.          */
  3537.         t = (char_u **)lalloc((long_u)(sizeof(char_u *) * (new_count + 1)), TRUE);
  3538.         if (t != NULL)
  3539.             for (i = new_count; --i >= 0; )
  3540.                 t[i] = new_files[i];
  3541.         vim_free(new_files);
  3542.         if (t == NULL)
  3543.             return FAIL;
  3544.         new_files = t;
  3545.         new_files[new_count++] = str;
  3546.  
  3547.         /*
  3548.          * isolate one argument, taking quotes
  3549.          */
  3550.         inquote = FALSE;
  3551.         for (p = str; *str; ++str)
  3552.         {
  3553.             /*
  3554.              * for MSDOS et.al. a backslash is part of a file name.
  3555.              * Only skip ", space and tab.
  3556.              */
  3557.             if (is_backslash(str))
  3558.                 *p++ = *++str;
  3559.             else
  3560.             {
  3561.                 if (!inquote && vim_isspace(*str))
  3562.                     break;
  3563.                 if (*str == '"')
  3564.                     inquote ^= TRUE;
  3565.                 else
  3566.                     *p++ = *str;
  3567.             }
  3568.         }
  3569.         str = skipwhite(str);
  3570.         *p = NUL;
  3571.     }
  3572.     
  3573.     i = ExpandWildCards(new_count, new_files, &exp_count,
  3574.                                                 &exp_files, FALSE, TRUE);
  3575.     vim_free(new_files);
  3576.     if (i == FAIL)
  3577.         return FAIL;
  3578.     if (exp_count == 0)
  3579.     {
  3580.         emsg(e_nomatch);
  3581.         return FAIL;
  3582.     }
  3583.     if (arg_exp)                /* arg_files[] has been allocated, free it */
  3584.         FreeWild(arg_count, arg_files);
  3585.     else
  3586.         arg_exp = TRUE;
  3587.     arg_files = exp_files;
  3588.     arg_count = exp_count;
  3589.     arg_had_last = FALSE;
  3590.  
  3591.     /*
  3592.      * put all file names in the buffer list
  3593.      */
  3594.     for (i = 0; i < arg_count; ++i)
  3595.         (void)buflist_add(arg_files[i]);
  3596.  
  3597.     return OK;
  3598. }
  3599.  
  3600. /*
  3601.  * Return TRUE if "str" starts with a backslash that should be removed.
  3602.  * For MS-DOS, WIN32 and OS/2 this is only done when the character after the
  3603.  * backslash is not a normal file name character.
  3604.  */
  3605.     static int
  3606. is_backslash(str)
  3607.     char_u    *str;
  3608. {
  3609. #ifdef BACKSLASH_IN_FILENAME
  3610.     return (str[0] == '\\' && str[1] != NUL &&
  3611.                                      !(isfilechar(str[1]) && str[1] != '\\'));
  3612. #else
  3613.     return (str[0] == '\\' && str[1] != NUL);
  3614. #endif
  3615. }
  3616.  
  3617. /*
  3618.  * Check if we are editing the w_arg_idx file in the argument list.
  3619.  */
  3620.     void
  3621. check_arg_idx()
  3622. {
  3623.     int        t;
  3624.  
  3625.     if (arg_count > 1 && (curbuf->b_filename == NULL ||
  3626.                           curwin->w_arg_idx >= arg_count ||
  3627.                 (t = fullpathcmp(arg_files[curwin->w_arg_idx],
  3628.                            curbuf->b_filename)) == FPC_DIFF || t == FPC_DIFFX))
  3629.         curwin->w_arg_idx_invalid = TRUE;
  3630.     else
  3631.         curwin->w_arg_idx_invalid = FALSE;
  3632. }
  3633.  
  3634.     void
  3635. gotocmdline(clr)
  3636.     int                clr;
  3637. {
  3638.     msg_start();
  3639.     if (clr)                /* clear the bottom line(s) */
  3640.         msg_clr_eos();        /* will reset clear_cmdline */
  3641.     windgoto(cmdline_row, 0);
  3642. }
  3643.  
  3644.     static int
  3645. check_readonly()
  3646. {
  3647.     if (!forceit && curbuf->b_p_ro)
  3648.     {
  3649.         emsg(e_readonly);
  3650.         return TRUE;
  3651.     }
  3652.     return FALSE;
  3653. }
  3654.  
  3655. /*
  3656.  * return TRUE if buffer was changed and cannot be abandoned.
  3657.  */
  3658.     static int
  3659. check_changed(buf, checkaw, mult_win)
  3660.     BUF        *buf;
  3661.     int        checkaw;        /* do autowrite if buffer was changed */
  3662.     int        mult_win;        /* check also when several windows for the buffer */
  3663. {
  3664.     if (    !forceit &&
  3665.             buf->b_changed && (mult_win || buf->b_nwindows <= 1) &&
  3666.             (!checkaw || autowrite(buf) == FAIL))
  3667.     {
  3668.         emsg(e_nowrtmsg);
  3669.         return TRUE;
  3670.     }
  3671.     return FALSE;
  3672. }
  3673.  
  3674. /*
  3675.  * return TRUE if any buffer was changed and cannot be abandoned.
  3676.  * That changed buffer becomes the current buffer.
  3677.  */
  3678.     static int
  3679. check_changed_any()
  3680. {
  3681.     BUF        *buf;
  3682.     int        save;
  3683.  
  3684.     if (!forceit)
  3685.     {
  3686.         for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  3687.         {
  3688.             if (buf->b_changed)
  3689.             {
  3690.                 /* There must be a wait_return for this message, do_buffer
  3691.                  * will cause a redraw */
  3692.                 exiting = FALSE;
  3693.                 if (EMSG2("No write since last change for buffer \"%s\"",
  3694.                               buf->b_xfilename == NULL ? (char_u *)"No File" :
  3695.                                                             buf->b_xfilename))
  3696.                 {
  3697.                     save = no_wait_return;
  3698.                     no_wait_return = FALSE;
  3699.                     wait_return(FALSE);
  3700.                     no_wait_return = save;
  3701.                 }
  3702.                 (void)do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD,
  3703.                                                               buf->b_fnum, 0);
  3704.                 return TRUE;
  3705.             }
  3706.         }
  3707.     }
  3708.     return FALSE;
  3709. }
  3710.  
  3711. /*
  3712.  * return FAIL if there is no filename, OK if there is one
  3713.  * give error message for FAIL
  3714.  */
  3715.     int
  3716. check_fname()
  3717. {
  3718.     if (curbuf->b_filename == NULL)
  3719.     {
  3720.         emsg(e_noname);
  3721.         return FAIL;
  3722.     }
  3723.     return OK;
  3724. }
  3725.  
  3726. /*
  3727.  * - if there are more files to edit
  3728.  * - and this is the last window
  3729.  * - and forceit not used
  3730.  * - and not repeated twice on a row
  3731.  *      return FAIL and give error message if 'message' TRUE
  3732.  * return OK otherwise
  3733.  */
  3734.     static int
  3735. check_more(message)
  3736.     int message;            /* when FALSE check only, no messages */
  3737. {
  3738.     if (!forceit && only_one_window() && arg_count > 1 && !arg_had_last &&
  3739.                                     quitmore == 0)
  3740.     {
  3741.         if (message)
  3742.         {
  3743.             EMSGN("%ld more files to edit", arg_count - curwin->w_arg_idx - 1);
  3744.             quitmore = 2;            /* next try to quit is allowed */
  3745.         }
  3746.         return FAIL;
  3747.     }
  3748.     return OK;
  3749. }
  3750.  
  3751. /*
  3752.  * try to abandon current file and edit a new or existing file
  3753.  * 'fnum' is the number of the file, if zero use fname/sfname
  3754.  *
  3755.  * return 1 for "normal" error, 2 for "not written" error, 0 for success
  3756.  * -1 for succesfully opening another file
  3757.  * 'lnum' is the line number for the cursor in the new file (if non-zero).
  3758.  */
  3759.     int
  3760. getfile(fnum, fname, sfname, setpm, lnum)
  3761.     int            fnum;
  3762.     char_u        *fname;
  3763.     char_u        *sfname;
  3764.     int            setpm;
  3765.     linenr_t    lnum;
  3766. {
  3767.     int other;
  3768.  
  3769.     if (fnum == 0)
  3770.     {
  3771.         fname_expand(&fname, &sfname);    /* make fname full path, set sfname */
  3772.         other = otherfile(fname);
  3773.     }
  3774.     else
  3775.         other = (fnum != curbuf->b_fnum);
  3776.  
  3777.     if (other)
  3778.         ++no_wait_return;            /* don't wait for autowrite message */
  3779.     if (other && !forceit && curbuf->b_nwindows == 1 &&
  3780.             !p_hid && curbuf->b_changed && autowrite(curbuf) == FAIL)
  3781.     {
  3782.         if (other)
  3783.             --no_wait_return;
  3784.         emsg(e_nowrtmsg);
  3785.         return 2;        /* file has been changed */
  3786.     }
  3787.     if (other)
  3788.         --no_wait_return;
  3789.     if (setpm)
  3790.         setpcmark();
  3791.     if (!other)
  3792.     {
  3793.         if (lnum != 0)
  3794.             curwin->w_cursor.lnum = lnum;
  3795.         check_cursor();
  3796.         beginline(MAYBE);
  3797.  
  3798.         return 0;        /* it's in the same file */
  3799.     }
  3800.     if (do_ecmd(fnum, fname, sfname, NULL, p_hid, lnum, FALSE) == OK)
  3801.         return -1;        /* opened another file */
  3802.     return 1;            /* error encountered */
  3803. }
  3804.  
  3805. /*
  3806.  * vim_strncpy()
  3807.  *
  3808.  * This is here because strncpy() does not guarantee successful results when
  3809.  * the to and from strings overlap.  It is only currently called from nextwild()
  3810.  * which copies part of the command line to another part of the command line.
  3811.  * This produced garbage when expanding files etc in the middle of the command
  3812.  * line (on my terminal, anyway) -- webb.
  3813.  */
  3814.     static void
  3815. vim_strncpy(to, from, len)
  3816.     char_u *to;
  3817.     char_u *from;
  3818.     int len;
  3819. {
  3820.     int i;
  3821.  
  3822.     if (to <= from)
  3823.     {
  3824.         while (len-- && *from)
  3825.             *to++ = *from++;
  3826.         if (len >= 0)
  3827.             *to = *from;    /* Copy NUL */
  3828.     }
  3829.     else
  3830.     {
  3831.         for (i = 0; i < len; i++)
  3832.         {
  3833.             to++;
  3834.             if (*from++ == NUL)
  3835.             {
  3836.                 i++;
  3837.                 break;
  3838.             }
  3839.         }
  3840.         for (; i > 0; i--)
  3841.             *--to = *--from;
  3842.     }
  3843. }
  3844.  
  3845. /*
  3846.  * Return FALSE if this is not an appropriate context in which to do
  3847.  * completion of anything, & TRUE if it is (even if there are no matches).
  3848.  * For the caller, this means that the character is just passed through like a
  3849.  * normal character (instead of being expanded).  This allows :s/^I^D etc.
  3850.  */
  3851.     static int
  3852. nextwild(type)
  3853.     int        type;
  3854. {
  3855.     int        i;
  3856.     char_u    *p1;
  3857.     char_u    *p2;
  3858.     int        oldlen;
  3859.     int        difflen;
  3860.     int        v;
  3861.  
  3862.     if (cmd_numfiles == -1)
  3863.         set_expand_context(cmdfirstc, cmdbuff);
  3864.     if (expand_context == EXPAND_UNSUCCESSFUL)
  3865.     {
  3866.         beep_flush();
  3867.         return OK;    /* Something illegal on command line */
  3868.     }
  3869.     if (expand_context == EXPAND_NOTHING)
  3870.     {
  3871.         /* Caller can use the character as a normal char instead */
  3872.         return FAIL;
  3873.     }
  3874.     expand_interactively = TRUE;
  3875.  
  3876.     MSG_OUTSTR("...");        /* show that we are busy */
  3877.     flushbuf();
  3878.  
  3879.     i = expand_pattern - cmdbuff;
  3880.     oldlen = cmdpos - i;
  3881.  
  3882.     if (type == WILD_NEXT || type == WILD_PREV)
  3883.     {
  3884.         /*
  3885.          * Get next/previous match for a previous expanded pattern.
  3886.          */
  3887.         p2 = ExpandOne(NULL, NULL, 0, type);
  3888.     }
  3889.     else
  3890.     {
  3891.         /*
  3892.          * Translate string into pattern and expand it.
  3893.          */
  3894.         if ((p1 = addstar(&cmdbuff[i], oldlen)) == NULL)
  3895.             p2 = NULL;
  3896.         else
  3897.         {
  3898.             p2 = ExpandOne(p1, strnsave(&cmdbuff[i], oldlen),
  3899.                                                      WILD_HOME_REPLACE, type);
  3900.             vim_free(p1);
  3901.         }
  3902.     }
  3903.  
  3904.     if (p2 != NULL)
  3905.     {
  3906.         if (cmdlen + (difflen = STRLEN(p2) - oldlen) > cmdbufflen - 4)
  3907.             v = realloc_cmdbuff(cmdlen + difflen);
  3908.         else
  3909.             v = OK;
  3910.         if (v == OK)
  3911.         {
  3912.             vim_strncpy(&cmdbuff[cmdpos + difflen], &cmdbuff[cmdpos],
  3913.                     cmdlen - cmdpos);
  3914.             STRNCPY(&cmdbuff[i], p2, STRLEN(p2));
  3915.             cmdlen += difflen;
  3916.             cmdpos += difflen;
  3917.         }
  3918.         vim_free(p2);
  3919.     }
  3920.  
  3921.     redrawcmd();
  3922.     if (cmd_numfiles <= 0 && p2 == NULL)
  3923.         beep_flush();
  3924.     else if (cmd_numfiles == 1)
  3925.         (void)ExpandOne(NULL, NULL, 0, WILD_FREE);    /* free expanded pattern */
  3926.  
  3927.     expand_interactively = FALSE;            /* reset for next call */
  3928.     return OK;
  3929. }
  3930.  
  3931. #define MAXSUFLEN 30        /* maximum length of a file suffix */
  3932.  
  3933. /*
  3934.  * Do wildcard expansion on the string 'str'.
  3935.  * Return a pointer to alloced memory containing the new string.
  3936.  * Return NULL for failure.
  3937.  *
  3938.  * mode = WILD_FREE:        just free previously expanded matches
  3939.  * mode = WILD_EXPAND_FREE:    normal expansion, do not keep matches
  3940.  * mode = WILD_EXPAND_KEEP:    normal expansion, keep matches
  3941.  * mode = WILD_NEXT:        use next match in multiple match, wrap to first
  3942.  * mode = WILD_PREV:        use previous match in multiple match, wrap to first
  3943.  * mode = WILD_ALL:            return all matches concatenated
  3944.  * mode = WILD_LONGEST:        return longest matched part
  3945.  *
  3946.  * options = WILD_LIST_NOTFOUND:    list entries without a match
  3947.  * options = WILD_HOME_REPLACE:        do home_replace() for buffer names
  3948.  */
  3949.     char_u *
  3950. ExpandOne(str, orig, options, mode)
  3951.     char_u    *str;
  3952.     char_u    *orig;            /* original string which is expanded */
  3953.     int        options;
  3954.     int        mode;
  3955. {
  3956.     char_u        *ss = NULL;
  3957.     static char_u **cmd_files = NULL;    /* list of input files */
  3958.     static int    findex;
  3959.     static char_u *orig_save = NULL;    /* kept value of orig */
  3960.     int            i, found = 0;
  3961.     int            multmatch = FALSE;
  3962.     long_u        len;
  3963.     char_u        *setsuf;
  3964.     int            fnamelen, setsuflen;
  3965.     char_u        suf_buf[MAXSUFLEN];
  3966.     char_u        *p;
  3967.  
  3968. /*
  3969.  * first handle the case of using an old match
  3970.  */
  3971.     if (mode == WILD_NEXT || mode == WILD_PREV)
  3972.     {
  3973.         if (cmd_numfiles > 0)
  3974.         {
  3975.             if (mode == WILD_PREV)
  3976.             {
  3977.                 if (findex == -1)
  3978.                     findex = cmd_numfiles;
  3979.                 --findex;
  3980.             }
  3981.             else    /* mode == WILD_NEXT */
  3982.                 ++findex;
  3983.  
  3984.             /*
  3985.              * When wrapping around, return the original string, set findex to
  3986.              * -1.
  3987.              */
  3988.             if (findex < 0)
  3989.             {
  3990.                 if (orig_save == NULL)
  3991.                     findex = cmd_numfiles - 1;
  3992.                 else
  3993.                     findex = -1;
  3994.             }
  3995.             if (findex >= cmd_numfiles)
  3996.             {
  3997.                 if (orig_save == NULL)
  3998.                     findex = 0;
  3999.                 else
  4000.                     findex = -1;
  4001.             }
  4002.             if (findex == -1)
  4003.                 return strsave(orig_save);
  4004.             return strsave(cmd_files[findex]);
  4005.         }
  4006.         else
  4007.             return NULL;
  4008.     }
  4009.  
  4010. /* free old names */
  4011.     if (cmd_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST)
  4012.     {
  4013.         FreeWild(cmd_numfiles, cmd_files);
  4014.         cmd_numfiles = -1;
  4015.         vim_free(orig_save);
  4016.         orig_save = NULL;
  4017.     }
  4018.     findex = 0;
  4019.  
  4020.     if (mode == WILD_FREE)        /* only release file name */
  4021.         return NULL;
  4022.  
  4023.     if (cmd_numfiles == -1)
  4024.     {
  4025.         vim_free(orig_save);
  4026.         orig_save = orig;
  4027.         if (ExpandFromContext(str, &cmd_numfiles, &cmd_files, FALSE,
  4028.                                                              options) == FAIL)
  4029.             /* error: do nothing */;
  4030.         else if (cmd_numfiles == 0)
  4031.         {
  4032.             if (!expand_interactively)
  4033.                 emsg(e_nomatch);
  4034.         }
  4035.         else
  4036.         {
  4037.             /*
  4038.              * If the pattern starts with a '~', replace the home diretory
  4039.              * with '~' again.
  4040.              */
  4041.             if (*str == '~' && (options & WILD_HOME_REPLACE))
  4042.             {
  4043.                 for (i = 0; i < cmd_numfiles; ++i)
  4044.                 {
  4045.                     p = home_replace_save(NULL, cmd_files[i]);
  4046.                     if (p != NULL)
  4047.                     {
  4048.                         vim_free(cmd_files[i]);
  4049.                         cmd_files[i] = p;
  4050.                     }
  4051.                 }
  4052.             }
  4053.  
  4054.             /*
  4055.              * Insert backslashes into a file name before a space, \, %, # and
  4056.              * wildmatch characters, except '~'.
  4057.              */
  4058.             if (expand_interactively &&
  4059.                     (expand_context == EXPAND_FILES ||
  4060.                      expand_context == EXPAND_BUFFERS ||
  4061.                      expand_context == EXPAND_DIRECTORIES))
  4062.             {
  4063.                 for (i = 0; i < cmd_numfiles; ++i)
  4064.                 {
  4065.                     p = strsave_escaped(cmd_files[i],
  4066. #ifdef BACKSLASH_IN_FILENAME
  4067.                                                     (char_u *)" *?[{`$%#");
  4068. #else
  4069.                                                     (char_u *)" *?[{`$\\%#");
  4070. #endif
  4071.                     if (p != NULL)
  4072.                     {
  4073.                         vim_free(cmd_files[i]);
  4074.                         cmd_files[i] = p;
  4075.                     }
  4076.                 }
  4077.             }
  4078.  
  4079.             if (mode != WILD_ALL && mode != WILD_LONGEST)
  4080.             {
  4081.                 if (cmd_numfiles > 1)    /* more than one match; check suffix */
  4082.                 {
  4083.                     found = -2;
  4084.                     for (i = 0; i < cmd_numfiles; ++i)
  4085.                     {
  4086.                         fnamelen = STRLEN(cmd_files[i]);
  4087.                         setsuflen = 0;
  4088.                         for (setsuf = p_su; *setsuf; )
  4089.                         {
  4090.                             setsuflen = copy_option_part(&setsuf, suf_buf,
  4091.                                                               MAXSUFLEN, ".,");
  4092.                             if (fnamelen >= setsuflen && STRNCMP(suf_buf,
  4093.                                           cmd_files[i] + fnamelen - setsuflen,
  4094.                                                       (size_t)setsuflen) == 0)
  4095.                                 break;
  4096.                             setsuflen = 0;
  4097.                         }
  4098.                         if (setsuflen)        /* suffix matched: ignore file */
  4099.                             continue;
  4100.                         if (found >= 0)
  4101.                         {
  4102.                             multmatch = TRUE;
  4103.                             break;
  4104.                         }
  4105.                         found = i;
  4106.                     }
  4107.                 }
  4108.                 if (multmatch || found < 0)
  4109.                 {
  4110.                     /* Can we ever get here unless it's while expanding
  4111.                      * interactively?  If not, we can get rid of this all
  4112.                      * together. Don't really want to wait for this message
  4113.                      * (and possibly have to hit return to continue!).
  4114.                      */
  4115.                     if (!expand_interactively)
  4116.                         emsg(e_toomany);
  4117.                     else
  4118.                         beep_flush();
  4119.                     found = 0;                /* return first one */
  4120.                     multmatch = TRUE;        /* for found < 0 */
  4121.                 }
  4122.                 if (found >= 0 && !(multmatch && mode == WILD_EXPAND_FREE))
  4123.                     ss = strsave(cmd_files[found]);
  4124.             }
  4125.         }
  4126.     }
  4127.  
  4128.     /* Find longest common part */
  4129.     if (mode == WILD_LONGEST && cmd_numfiles > 0)
  4130.     {
  4131.         for (len = 0; cmd_files[0][len]; ++len)
  4132.         {
  4133.             for (i = 0; i < cmd_numfiles; ++i)
  4134.             {
  4135. #ifdef CASE_INSENSITIVE_FILENAME
  4136.                 if ((expand_context == EXPAND_DIRECTORIES ||
  4137.                                              expand_context == EXPAND_FILES ||
  4138.                                           expand_context == EXPAND_BUFFERS) &&
  4139.                      toupper(cmd_files[i][len]) != toupper(cmd_files[0][len]))
  4140.                     break;
  4141.                 else
  4142. #endif
  4143.                 if (cmd_files[i][len] != cmd_files[0][len])
  4144.                     break;
  4145.             }
  4146.             if (i < cmd_numfiles)
  4147.             {
  4148.                 vim_beep();
  4149.                 break;
  4150.             }
  4151.         }
  4152.         ss = alloc((unsigned)len + 1);
  4153.         if (ss)
  4154.         {
  4155.             STRNCPY(ss, cmd_files[0], len);
  4156.             ss[len] = NUL;
  4157.         }
  4158.         findex = -1;                        /* next p_wc gets first one */
  4159.     }
  4160.  
  4161.     /* Concatenate all matching names */
  4162.     if (mode == WILD_ALL && cmd_numfiles > 0)
  4163.     {
  4164.         len = 0;
  4165.         for (i = 0; i < cmd_numfiles; ++i)
  4166.             len += STRLEN(cmd_files[i]) + 1;
  4167.         ss = lalloc(len, TRUE);
  4168.         if (ss)
  4169.         {
  4170.             *ss = NUL;
  4171.             for (i = 0; i < cmd_numfiles; ++i)
  4172.             {
  4173.                 STRCAT(ss, cmd_files[i]);
  4174.                 if (i != cmd_numfiles - 1)
  4175.                     STRCAT(ss, " ");
  4176.             }
  4177.         }
  4178.     }
  4179.  
  4180.     if (mode == WILD_EXPAND_FREE || mode == WILD_ALL)
  4181.     {
  4182.         FreeWild(cmd_numfiles, cmd_files);
  4183.         cmd_numfiles = -1;
  4184.     }
  4185.     return ss;
  4186. }
  4187.  
  4188. /*
  4189.  * show all matches for completion on the command line
  4190.  */
  4191.     static int
  4192. showmatches(buff)
  4193.     char_u *buff;
  4194. {
  4195.     char_u        *file_str;
  4196.     int            num_files;
  4197.     char_u        **files_found;
  4198.     int            i, j, k;
  4199.     int            maxlen;
  4200.     int            lines;
  4201.     int            columns;
  4202.     char_u        *p;
  4203.     int            lastlen;
  4204.  
  4205.     set_expand_context(cmdfirstc, cmdbuff);
  4206.     if (expand_context == EXPAND_UNSUCCESSFUL)
  4207.     {
  4208.         beep_flush();
  4209.         return OK;    /* Something illegal on command line */
  4210.     }
  4211.     if (expand_context == EXPAND_NOTHING)
  4212.     {
  4213.         /* Caller can use the character as a normal char instead */
  4214.         return FAIL;
  4215.     }
  4216.     expand_interactively = TRUE;
  4217.  
  4218.     /* add star to file name, or convert to regexp if not expanding files! */
  4219.     file_str = addstar(expand_pattern, (int)(buff + cmdpos - expand_pattern));
  4220.     if (file_str == NULL)
  4221.     {
  4222.         expand_interactively = FALSE;
  4223.         return OK;
  4224.     }
  4225.  
  4226.     msg_didany = FALSE;                    /* lines_left will be set */
  4227.     msg_start();                        /* prepare for paging */
  4228.     msg_outchar('\n');
  4229.     flushbuf();
  4230.     cmdline_row = msg_row;
  4231.     msg_didany = FALSE;                    /* lines_left will be set again */
  4232.     msg_start();                        /* prepare for paging */
  4233.  
  4234.     /* find all files that match the description */
  4235.     if (ExpandFromContext(file_str, &num_files, &files_found, FALSE, 0) == FAIL)
  4236.     {
  4237.         num_files = 0;
  4238.         files_found = (char_u **)"";
  4239.     }
  4240.  
  4241.     /* find the length of the longest file name */
  4242.     maxlen = 0;
  4243.     for (i = 0; i < num_files; ++i)
  4244.     {
  4245.         if (expand_context == EXPAND_FILES || expand_context == EXPAND_BUFFERS)
  4246.         {
  4247.             home_replace(NULL, files_found[i], NameBuff, MAXPATHL);
  4248.             j = strsize(NameBuff);
  4249.         }
  4250.         else
  4251.             j = strsize(files_found[i]);
  4252.         if (j > maxlen)
  4253.             maxlen = j;
  4254.     }
  4255.  
  4256.     /* compute the number of columns and lines for the listing */
  4257.     maxlen += 2;    /* two spaces between file names */
  4258.     columns = ((int)Columns + 2) / maxlen;
  4259.     if (columns < 1)
  4260.         columns = 1;
  4261.     lines = (num_files + columns - 1) / columns;
  4262.  
  4263.     (void)set_highlight('d');    /* find out highlight mode for directories */
  4264.  
  4265.     /* list the files line by line */
  4266.     for (i = 0; i < lines; ++i)
  4267.     {
  4268.         lastlen = 999;
  4269.         for (k = i; k < num_files; k += lines)
  4270.         {
  4271.             for (j = maxlen - lastlen; --j >= 0; )
  4272.                 msg_outchar(' ');
  4273.             if (expand_context == EXPAND_FILES ||
  4274.                                              expand_context == EXPAND_BUFFERS)
  4275.             {
  4276.                         /* highlight directories */
  4277.                 j = (mch_isdir(files_found[k]));
  4278.                 home_replace(NULL, files_found[k], NameBuff, MAXPATHL);
  4279.                 p = NameBuff;
  4280.             }
  4281.             else
  4282.             {
  4283.                 j = FALSE;
  4284.                 p = files_found[k];
  4285.             }
  4286.             if (j)
  4287.                 start_highlight();
  4288.             lastlen = msg_outtrans(p);
  4289.             if (j)
  4290.                 stop_highlight();
  4291.         }
  4292.         msg_outchar('\n');
  4293.         flushbuf();                    /* show one line at a time */
  4294.         if (got_int)
  4295.         {
  4296.             got_int = FALSE;
  4297.             break;
  4298.         }
  4299.     }
  4300.     vim_free(file_str);
  4301.     FreeWild(num_files, files_found);
  4302.  
  4303. /*
  4304.  * we redraw the command below the lines that we have just listed
  4305.  * This is a bit tricky, but it saves a lot of screen updating.
  4306.  */
  4307.     cmdline_row = msg_row;        /* will put it back later */
  4308.  
  4309.     expand_interactively = FALSE;
  4310.     return OK;
  4311. }
  4312.  
  4313. /*
  4314.  * Prepare a string for expansion.
  4315.  * When expanding file names:  The string will be used with ExpandWildCards().
  4316.  * Copy the file name into allocated memory and add a '*' at the end.
  4317.  * When expanding other names:  The string will be used with regcomp().  Copy
  4318.  * the name into allocated memory and add ".*" at the end.
  4319.  */
  4320.     char_u *
  4321. addstar(fname, len)
  4322.     char_u    *fname;
  4323.     int        len;
  4324. {
  4325.     char_u    *retval;
  4326.     int        i, j;
  4327.     int        new_len;
  4328.     char_u    *tail;
  4329.  
  4330.     if (expand_interactively && expand_context != EXPAND_FILES &&
  4331.                                          expand_context != EXPAND_DIRECTORIES)
  4332.     {
  4333.         /*
  4334.          * Matching will be done internally (on something other than files).
  4335.          * So we convert the file-matching-type wildcards into our kind for
  4336.          * use with vim_regcomp().  First work out how long it will be:
  4337.          */
  4338.  
  4339.         /* for help tags the translation is done in find_help_tags() */
  4340.         if (expand_context == EXPAND_HELP)
  4341.             retval = strnsave(fname, len);
  4342.         else
  4343.         {
  4344.             new_len = len + 2;            /* +2 for '^' at start, NUL at end */
  4345.             for (i = 0; i < len; i++)
  4346.             {
  4347.                 if (fname[i] == '*' || fname[i] == '~')
  4348.                     new_len++;            /* '*' needs to be replaced by ".*"
  4349.                                            '~' needs to be replaced by "\~" */
  4350.  
  4351.                 /* Buffer names are like file names.  "." should be literal */
  4352.                 if (expand_context == EXPAND_BUFFERS && fname[i] == '.')
  4353.                     new_len++;            /* "." becomes "\." */
  4354.             }
  4355.             retval = alloc(new_len);
  4356.             if (retval != NULL)
  4357.             {
  4358.                 retval[0] = '^';
  4359.                 j = 1;
  4360.                 for (i = 0; i < len; i++, j++)
  4361.                 {
  4362.                     if (fname[i] == '\\' && ++i == len)    /* skip backslash */
  4363.                         break;
  4364.  
  4365.                     switch (fname[i])
  4366.                     {
  4367.                         case '*':    retval[j++] = '.';
  4368.                                     break;
  4369.                         case '~':    retval[j++] = '\\';
  4370.                                     break;
  4371.                         case '?':    retval[j] = '.';
  4372.                                     continue;
  4373.                         case '.':    if (expand_context == EXPAND_BUFFERS)
  4374.                                         retval[j++] = '\\';
  4375.                                     break;
  4376.                     }
  4377.                     retval[j] = fname[i];
  4378.                 }
  4379.                 retval[j] = NUL;
  4380.             }
  4381.         }
  4382.     }
  4383.     else
  4384.     {
  4385.         retval = alloc(len + 4);
  4386.         if (retval != NULL)
  4387.         {
  4388.             STRNCPY(retval, fname, len);
  4389.             retval[len] = NUL;
  4390.             backslash_halve(retval, TRUE);        /* remove some backslashes */
  4391.             len = STRLEN(retval);
  4392.  
  4393.             /*
  4394.              * Don't add a star to ~, ~user, $var or `cmd`.
  4395.              * ~ would be at the start of the tail.
  4396.              * $ could be anywhere in the tail.
  4397.              * ` could be anywhere in the file name.
  4398.              */
  4399.             tail = gettail(retval);
  4400.             if (*tail != '~' && vim_strchr(tail, '$') == NULL
  4401.                                            && vim_strchr(retval, '`') == NULL)
  4402.             {
  4403. #ifdef MSDOS
  4404.                 /*
  4405.                  * if there is no dot in the file name, add "*.*" instead of
  4406.                  * "*".
  4407.                  */
  4408.                 for (i = len - 1; i >= 0; --i)
  4409.                     if (vim_strchr((char_u *)".\\/:", retval[i]) != NULL)
  4410.                         break;
  4411.                 if (i < 0 || retval[i] != '.')
  4412.                 {
  4413.                     retval[len++] = '*';
  4414.                     retval[len++] = '.';
  4415.                 }
  4416. #endif
  4417.                 retval[len++] = '*';
  4418.             }
  4419.             retval[len] = NUL;
  4420.         }
  4421.     }
  4422.     return retval;
  4423. }
  4424.  
  4425. /*
  4426.  * do_source: read the file "fname" and execute its lines as EX commands
  4427.  *
  4428.  * This function may be called recursively!
  4429.  *
  4430.  * return FAIL if file could not be opened, OK otherwise
  4431.  */
  4432.     int
  4433. do_source(fname, check_other)
  4434.     register char_u *fname;
  4435.     int                check_other;        /* check for .vimrc and _vimrc */
  4436. {
  4437.     register FILE    *fp;
  4438.     register int    len;
  4439. #ifdef USE_CRNL
  4440.     int                has_cr;
  4441.     int                textmode = -1;    /* -1 = unknown, 0 = NL, 1 = CR-NL */
  4442.     int                error = FALSE;
  4443. #endif
  4444.                                     /* use NameBuff for expanded name */
  4445.     expand_env(fname, NameBuff, MAXPATHL);
  4446.     fp = fopen((char *)NameBuff, READBIN);
  4447.     if (fp == NULL && check_other)
  4448.     {
  4449.         /*
  4450.          * Try again, replacing file name ".vimrc" by "_vimrc" or vice versa
  4451.          * (if applicable)
  4452.          */
  4453.         len = STRLEN(NameBuff);
  4454.         if (((len > 6 && ispathsep(NameBuff[len - 7])) || len == 6) &&
  4455.                      (NameBuff[len - 6] == '.' || NameBuff[len - 6] == '_') &&
  4456.                                   (STRCMP(&NameBuff[len - 5], "vimrc") == 0))
  4457.         {
  4458.             if (NameBuff[len - 6] == '_')
  4459.                 NameBuff[len - 6] = '.';
  4460.             else
  4461.                 NameBuff[len - 6] = '_';
  4462.             fp = fopen((char *)NameBuff, READBIN);
  4463.         }
  4464.     }
  4465.  
  4466.     if (fp == NULL)
  4467.         return FAIL;
  4468.  
  4469. #ifdef USE_CRNL
  4470.         /* no automatic textmode: Set default to CR-NL */
  4471.     if (!p_ta)
  4472.         textmode = 1;
  4473. #endif
  4474.     sourcing_name = fname;
  4475.     sourcing_lnum = 1;
  4476. #ifdef SLEEP_IN_EMSG
  4477.     ++dont_sleep;            /* don't call sleep() in emsg() */
  4478. #endif
  4479.     len = 0;
  4480.     while (fgets((char *)IObuff + len, IOSIZE - len, fp) != NULL && !got_int)
  4481.     {
  4482.         len = STRLEN(IObuff) - 1;
  4483.         if (len >= 0 && IObuff[len] == '\n')    /* remove trailing newline */
  4484.         {
  4485. #ifdef USE_CRNL
  4486.             has_cr = (len > 0 && IObuff[len - 1] == '\r');
  4487.             if (textmode == -1)
  4488.             {
  4489.                 if (has_cr)
  4490.                     textmode = 1;
  4491.                 else
  4492.                     textmode = 0;
  4493.             }
  4494.  
  4495.             if (textmode)
  4496.             {
  4497.                 if (has_cr)         /* remove trailing CR-LF */
  4498.                     --len;
  4499.                 else        /* lines like ":map xx yy^M" will have failed */
  4500.                 {
  4501.                     if (!error)
  4502.                         EMSG("Warning: Wrong line separator, ^M may be missing");
  4503.                     error = TRUE;
  4504.                     textmode = 0;
  4505.                 }
  4506.             }
  4507. #endif
  4508.                 /* escaped newline, read more */
  4509.             if (len > 0 && len < IOSIZE && IObuff[len - 1] == Ctrl('V'))
  4510.             {
  4511.                 IObuff[len - 1] = '\n';        /* remove CTRL-V */
  4512.                 ++sourcing_lnum;
  4513.                 continue;
  4514.             }
  4515.             IObuff[len] = NUL;
  4516.         }
  4517.             /* check for ^C here, so recursive :so will be broken */
  4518.         mch_breakcheck();
  4519.         do_cmdline(IObuff, TRUE, TRUE);
  4520.         len = 0;
  4521.         ++sourcing_lnum;
  4522.     }
  4523.     fclose(fp);
  4524.     if (got_int)
  4525.         emsg(e_interr);
  4526. #ifdef SLEEP_IN_EMSG
  4527.     --dont_sleep;
  4528. #endif
  4529.     sourcing_name = NULL;
  4530.     sourcing_lnum = 0;
  4531.     return OK;
  4532. }
  4533.  
  4534. /*
  4535.  * get a single EX address
  4536.  * 
  4537.  * Set ptr to the next character after the part that was interpreted.
  4538.  * Set ptr to NULL when an error is encountered.
  4539.  */
  4540.     static linenr_t
  4541. get_address(ptr)
  4542.     char_u        **ptr;
  4543. {
  4544.     linenr_t    cursor_lnum = curwin->w_cursor.lnum;
  4545.     int            c;
  4546.     int            i;
  4547.     long        n;
  4548.     char_u      *cmd;
  4549.     FPOS        pos;
  4550.     FPOS        *fp;
  4551.     linenr_t    lnum;
  4552.  
  4553.     cmd = skipwhite(*ptr);
  4554.     lnum = MAXLNUM;
  4555.     do
  4556.     {
  4557.         switch (*cmd)
  4558.         {
  4559.             case '.':                         /* '.' - Cursor position */
  4560.                         ++cmd;
  4561.                         lnum = cursor_lnum;
  4562.                         break;
  4563.  
  4564.             case '$':                         /* '$' - last line */
  4565.                         ++cmd;
  4566.                         lnum = curbuf->b_ml.ml_line_count;
  4567.                         break;
  4568.  
  4569.             case '\'':                         /* ''' - mark */
  4570.                         if (*++cmd == NUL || (check_mark(
  4571.                                         fp = getmark(*cmd++, FALSE)) == FAIL))
  4572.                             goto error;
  4573.                         lnum = fp->lnum;
  4574.                         break;
  4575.  
  4576.             case '/':
  4577.             case '?':                        /* '/' or '?' - search */
  4578.                         c = *cmd++;
  4579.                         pos = curwin->w_cursor;        /* save curwin->w_cursor */
  4580.                         if (c == '/')    /* forward search, start on next line */
  4581.                         {
  4582.                             ++curwin->w_cursor.lnum;
  4583.                             curwin->w_cursor.col = 0;
  4584.                         }
  4585.                         else           /* backward search, start on prev line */
  4586.                         {
  4587.                             --curwin->w_cursor.lnum;
  4588.                             curwin->w_cursor.col = MAXCOL;
  4589.                         }
  4590.                         searchcmdlen = 0;
  4591.                         if (!do_search(c, cmd, 1L,
  4592.                                       SEARCH_HIS + SEARCH_MSG + SEARCH_START))
  4593.                         {
  4594.                             cmd = NULL;
  4595.                             curwin->w_cursor = pos;
  4596.                             goto error;
  4597.                         }
  4598.                         lnum = curwin->w_cursor.lnum;
  4599.                         curwin->w_cursor = pos;
  4600.                                             /* adjust command string pointer */
  4601.                         cmd += searchcmdlen;
  4602.                         break;
  4603.  
  4604.             case '\\':                /* "\?", "\/" or "\&", repeat search */
  4605.                         ++cmd;
  4606.                         if (*cmd == '&')
  4607.                             i = RE_SUBST;
  4608.                         else if (*cmd == '?' || *cmd == '/')
  4609.                             i = RE_SEARCH;
  4610.                         else
  4611.                         {
  4612.                             emsg(e_backslash);
  4613.                             cmd = NULL;
  4614.                             goto error;
  4615.                         }
  4616.  
  4617.                                     /* forward search, start on next line */
  4618.                         if (*cmd != '?')
  4619.                         {
  4620.                             pos.lnum = curwin->w_cursor.lnum + 1;
  4621.                             pos.col = 0;
  4622.                         }
  4623.                                     /* backward search, start on prev line */
  4624.                         else        
  4625.                         {
  4626.                             pos.lnum = curwin->w_cursor.lnum - 1;
  4627.                             pos.col = MAXCOL;
  4628.                         }
  4629.                         if (searchit(&pos, *cmd == '?' ? BACKWARD : FORWARD,
  4630.                                                              (char_u *)"", 1L,
  4631.                                           SEARCH_MSG + SEARCH_START, i) == OK)
  4632.                             lnum = pos.lnum;
  4633.                         else
  4634.                         {
  4635.                             cmd = NULL;
  4636.                             goto error;
  4637.                         }
  4638.                         ++cmd;
  4639.                         break;
  4640.  
  4641.             default:
  4642.                         if (isdigit(*cmd))        /* absolute line number */
  4643.                             lnum = getdigits(&cmd);
  4644.         }
  4645.         
  4646.         for (;;)
  4647.         {
  4648.             cmd = skipwhite(cmd);
  4649.             if (*cmd != '-' && *cmd != '+' && !isdigit(*cmd))
  4650.                 break;
  4651.  
  4652.             if (lnum == MAXLNUM)
  4653.                 lnum = cursor_lnum;        /* "+1" is same as ".+1" */
  4654.             if (isdigit(*cmd))
  4655.                 i = '+';                /* "number" is same as "+number" */
  4656.             else
  4657.                 i = *cmd++;
  4658.             if (!isdigit(*cmd))            /* '+' is '+1', but '+0' is not '+1' */
  4659.                 n = 1;
  4660.             else 
  4661.                 n = getdigits(&cmd);
  4662.             if (i == '-')
  4663.                 lnum -= n;
  4664.             else
  4665.                 lnum += n;
  4666.         }
  4667.         cursor_lnum = lnum;
  4668.     } while (*cmd == '/' || *cmd == '?');
  4669.  
  4670. error:
  4671.     *ptr = cmd;
  4672.     return lnum;
  4673. }
  4674.  
  4675.  
  4676. /*
  4677.  * Must parse the command line so far to work out what context we are in.
  4678.  * Completion can then be done based on that context.
  4679.  * This routine sets two global variables:
  4680.  *    char_u *expand_pattern    The start of the pattern to be expanded within
  4681.  *                                the command line (ends at the cursor).
  4682.  *    int expand_context        The type of thing to expand.  Will be one of:
  4683.  *
  4684.  *    EXPAND_UNSUCCESSFUL        Used sometimes when there is something illegal on
  4685.  *                            the command line, like an unknown command.  Caller
  4686.  *                            should beep.
  4687.  *    EXPAND_NOTHING            Unrecognised context for completion, use char like
  4688.  *                            a normal char, rather than for completion.  eg
  4689.  *                            :s/^I/
  4690.  *    EXPAND_COMMANDS            Cursor is still touching the command, so complete
  4691.  *                            it.
  4692.  *    EXPAND_BUFFERS            Complete file names for :buf and :sbuf commands.
  4693.  *    EXPAND_FILES            After command with XFILE set, or after setting
  4694.  *                              with P_EXPAND set.  eg :e ^I, :w>>^I
  4695.  *    EXPAND_DIRECTORIES        In some cases this is used instead of the latter
  4696.  *                              when we know only directories are of interest.  eg
  4697.  *                              :set dir=^I
  4698.  *    EXPAND_SETTINGS            Complete variable names.  eg :set d^I
  4699.  *    EXPAND_BOOL_SETTINGS    Complete boolean variables only,  eg :set no^I
  4700.  *    EXPAND_TAGS                Complete tags from the files in p_tags.  eg :ta a^I
  4701.  *    EXPAND_HELP                Complete tags from the file 'helpfile'/vim_tags
  4702.  *    EXPAND_EVENTS            Complete event names
  4703.  *
  4704.  * -- webb.
  4705.  */
  4706.     static void
  4707. set_expand_context(firstc, buff)
  4708.     int            firstc;     /* either ':', '/', or '?' */
  4709.     char_u        *buff;         /* buffer for command string */
  4710. {
  4711.     char_u        *nextcomm;
  4712.     char_u        old_char;
  4713.  
  4714.     old_char = cmdbuff[cmdpos];
  4715.     cmdbuff[cmdpos] = NUL;
  4716.     nextcomm = buff;
  4717.     while (nextcomm != NULL)
  4718.         nextcomm = set_one_cmd_context(firstc, nextcomm);
  4719.     cmdbuff[cmdpos] = old_char;
  4720. }
  4721.  
  4722. /*
  4723.  * This is all pretty much copied from do_one_cmd(), with all the extra stuff
  4724.  * we don't need/want deleted.  Maybe this could be done better if we didn't
  4725.  * repeat all this stuff.  The only problem is that they may not stay perfectly
  4726.  * compatible with each other, but then the command line syntax probably won't
  4727.  * change that much -- webb.
  4728.  */
  4729.     static char_u *
  4730. set_one_cmd_context(firstc, buff)
  4731.     int            firstc;     /* either ':', '/', or '?' */
  4732.     char_u        *buff;         /* buffer for command string */
  4733. {
  4734.     char_u                *p;
  4735.     char_u                *cmd, *arg;
  4736.     int                 i;
  4737.     int                    cmdidx;
  4738.     long                argt;
  4739.     char_u                delim;
  4740.     int                    forced = FALSE;
  4741.     int                    usefilter = FALSE;    /* filter instead of file name */
  4742.  
  4743.     expand_pattern = buff;
  4744.     if (firstc != ':')
  4745.     {
  4746.         expand_context = EXPAND_NOTHING;
  4747.         return NULL;
  4748.     }
  4749.     expand_context = EXPAND_COMMANDS;    /* Default until we get past command */
  4750.  
  4751. /*
  4752.  * 2. skip comment lines and leading space, colons or bars
  4753.  */
  4754.     for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
  4755.         ;
  4756.     expand_pattern = cmd;
  4757.  
  4758.     if (*cmd == NUL)
  4759.         return NULL;
  4760.     if (*cmd == '"')        /* ignore comment lines */
  4761.     {
  4762.         expand_context = EXPAND_NOTHING;
  4763.         return NULL;
  4764.     }
  4765.  
  4766. /*
  4767.  * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
  4768.  */
  4769.     /* 
  4770.      * Backslashed delimiters after / or ? will be skipped, and commands will
  4771.      * not be expanded between /'s and ?'s or after "'". -- webb
  4772.      */
  4773.     while (*cmd != NUL && (vim_isspace(*cmd) || isdigit(*cmd) ||
  4774.                             vim_strchr((char_u *)".$%'/?-+,;", *cmd) != NULL))
  4775.     {
  4776.         if (*cmd == '\'')
  4777.         {
  4778.             if (*++cmd == NUL)
  4779.                 expand_context = EXPAND_NOTHING;
  4780.         }
  4781.         else if (*cmd == '/' || *cmd == '?')
  4782.         {
  4783.             delim = *cmd++;
  4784.             while (*cmd != NUL && *cmd != delim)
  4785.                 if (*cmd++ == '\\' && *cmd != NUL)
  4786.                     ++cmd;
  4787.             if (*cmd == NUL)
  4788.                 expand_context = EXPAND_NOTHING;
  4789.         }
  4790.         if (*cmd != NUL)
  4791.             ++cmd;
  4792.     }
  4793.  
  4794. /*
  4795.  * 4. parse command
  4796.  */
  4797.  
  4798.     cmd = skipwhite(cmd);
  4799.     expand_pattern = cmd;
  4800.     if (*cmd == NUL)
  4801.         return NULL;
  4802.     if (*cmd == '"')
  4803.     {
  4804.         expand_context = EXPAND_NOTHING;
  4805.         return NULL;
  4806.     }
  4807.  
  4808.     if (*cmd == '|' || *cmd == '\n')
  4809.         return cmd + 1;                    /* There's another command */
  4810.  
  4811.     /*
  4812.      * Isolate the command and search for it in the command table.
  4813.      * Exeptions:
  4814.      * - the 'k' command can directly be followed by any character.
  4815.      * - the 's' command can be followed directly by 'c', 'g' or 'r'
  4816.      */
  4817.     if (*cmd == 'k')
  4818.     {
  4819.         cmdidx = CMD_k;
  4820.         p = cmd + 1;
  4821.     }
  4822.     else
  4823.     {
  4824.         p = cmd;
  4825.         while (isalpha(*p) || *p == '*')    /* Allow * wild card */
  4826.             ++p;
  4827.             /* check for non-alpha command */
  4828.         if (p == cmd && vim_strchr((char_u *)"@!=><&~#", *p) != NULL)
  4829.             ++p;
  4830.         i = (int)(p - cmd);
  4831.  
  4832.         if (i == 0)
  4833.         {
  4834.             expand_context = EXPAND_UNSUCCESSFUL;
  4835.             return NULL;
  4836.         }
  4837.         for (cmdidx = 0; cmdidx < CMD_SIZE; ++cmdidx)
  4838.             if (STRNCMP(cmdnames[cmdidx].cmd_name, cmd, (size_t)i) == 0)
  4839.                 break;
  4840.     }
  4841.  
  4842.     /*
  4843.      * If the cursor is touching the command, and it ends in an alphabetic
  4844.      * character, complete the command name.
  4845.      */
  4846.     if (p == cmdbuff + cmdpos && isalpha(p[-1]))
  4847.         return NULL;
  4848.  
  4849.     if (cmdidx == CMD_SIZE)
  4850.     {
  4851.         if (*cmd == 's' && vim_strchr((char_u *)"cgr", cmd[1]) != NULL)
  4852.         {
  4853.             cmdidx = CMD_substitute;
  4854.             p = cmd + 1;
  4855.         }
  4856.         else
  4857.         {
  4858.             /* Not still touching the command and it was an illegal command */
  4859.             expand_context = EXPAND_UNSUCCESSFUL;
  4860.             return NULL;
  4861.         }
  4862.     }
  4863.  
  4864.     expand_context = EXPAND_NOTHING; /* Default now that we're past command */
  4865.  
  4866.     if (*p == '!')                    /* forced commands */
  4867.     {
  4868.         forced = TRUE;
  4869.         ++p;
  4870.     }
  4871.  
  4872. /*
  4873.  * 5. parse arguments
  4874.  */
  4875.     argt = cmdnames[cmdidx].cmd_argt;
  4876.  
  4877.     arg = skipwhite(p);
  4878.  
  4879.     if (cmdidx == CMD_write)
  4880.     {
  4881.         if (*arg == '>')                        /* append */
  4882.         {
  4883.             if (*++arg == '>')                /* It should be */
  4884.                 ++arg;
  4885.             arg = skipwhite(arg);
  4886.         }
  4887.         else if (*arg == '!')                    /* :w !filter */
  4888.         {
  4889.             ++arg;
  4890.             usefilter = TRUE;
  4891.         }
  4892.     }
  4893.  
  4894.     if (cmdidx == CMD_read)
  4895.     {
  4896.         usefilter = forced;                    /* :r! filter if forced */
  4897.         if (*arg == '!')                        /* :r !filter */
  4898.         {
  4899.             ++arg;
  4900.             usefilter = TRUE;
  4901.         }
  4902.     }
  4903.  
  4904.     if (cmdidx == CMD_lshift || cmdidx == CMD_rshift)
  4905.     {
  4906.         while (*arg == *cmd)        /* allow any number of '>' or '<' */
  4907.             ++arg;
  4908.         arg = skipwhite(arg);
  4909.     }
  4910.  
  4911.     /* Does command allow "+command"? */
  4912.     if ((argt & EDITCMD) && !usefilter && *arg == '+')
  4913.     {
  4914.         /* Check if we're in the +command */
  4915.         p = arg + 1;
  4916.         arg = skiptowhite(arg);
  4917.  
  4918.         /* Still touching the command after '+'? */
  4919.         if (arg >= cmdbuff + cmdpos)
  4920.             return p;
  4921.  
  4922.         /* Skip space after +command to get to the real argument */
  4923.         arg = skipwhite(arg);
  4924.     }
  4925.  
  4926.     /*
  4927.      * Check for '|' to separate commands and '"' to start comments.
  4928.      * Don't do this for ":read !cmd" and ":write !cmd".
  4929.      */
  4930.     if ((argt & TRLBAR) && !usefilter)
  4931.     {
  4932.         p = arg;
  4933.         while (*p)
  4934.         {
  4935.             if (*p == Ctrl('V'))
  4936.             {
  4937.                 if (p[1] != NUL)
  4938.                     ++p;
  4939.             }
  4940.             else if ((*p == '"' && !(argt & NOTRLCOM)) || *p == '|' || *p == '\n')
  4941.             {
  4942.                 if (*(p - 1) != '\\')
  4943.                 {
  4944.                     if (*p == '|' || *p == '\n')
  4945.                         return p + 1;
  4946.                     return NULL;    /* It's a comment */
  4947.                 }
  4948.             }
  4949.             ++p;
  4950.         }
  4951.     }
  4952.  
  4953.                                                 /* no arguments allowed */
  4954.     if (!(argt & EXTRA) && *arg != NUL &&
  4955.                                     vim_strchr((char_u *)"|\"", *arg) == NULL)
  4956.         return NULL;
  4957.  
  4958.     /* Find start of last argument (argument just before cursor): */
  4959.     p = cmdbuff + cmdpos;
  4960.     while (p != arg && *p != ' ' && *p != TAB)
  4961.         p--;
  4962.     if (*p == ' ' || *p == TAB)
  4963.         p++;
  4964.     expand_pattern = p;
  4965.  
  4966.     if (argt & XFILE)
  4967.     {
  4968.         int in_quote = FALSE;
  4969.         char_u *bow = NULL;        /* Beginning of word */
  4970.  
  4971.         /*
  4972.          * Allow spaces within back-quotes to count as part of the argument
  4973.          * being expanded.
  4974.          */
  4975.         expand_pattern = skipwhite(arg);
  4976.         for (p = expand_pattern; *p; ++p)
  4977.         {
  4978.             if (*p == '\\' && p[1])
  4979.                 ++p;
  4980. #ifdef SPACE_IN_FILENAME
  4981.             else if (vim_iswhite(*p) && (!(argt & NOSPC) || usefilter))
  4982. #else
  4983.             else if (vim_iswhite(*p))
  4984. #endif
  4985.             {
  4986.                 p = skipwhite(p);
  4987.                 if (in_quote)
  4988.                     bow = p;
  4989.                 else
  4990.                     expand_pattern = p;
  4991.                 --p;
  4992.             }
  4993.             else if (*p == '`')
  4994.             {
  4995.                 if (!in_quote)
  4996.                 {
  4997.                     expand_pattern = p;
  4998.                     bow = p + 1;
  4999.                 }
  5000.                 in_quote = !in_quote;
  5001.             }
  5002.         }
  5003.  
  5004.         /*
  5005.          * If we are still inside the quotes, and we passed a space, just
  5006.          * expand from there.
  5007.          */
  5008.         if (bow != NULL && in_quote)
  5009.             expand_pattern = bow;
  5010.         expand_context = EXPAND_FILES;
  5011.     }
  5012.  
  5013. /*
  5014.  * 6. switch on command name
  5015.  */
  5016.     switch (cmdidx)
  5017.     {
  5018.         case CMD_cd:
  5019.         case CMD_chdir:
  5020.             expand_context = EXPAND_DIRECTORIES;
  5021.             break;
  5022.         case CMD_global:
  5023.         case CMD_vglobal:
  5024.             delim = *arg;             /* get the delimiter */
  5025.             if (delim)
  5026.                 ++arg;                /* skip delimiter if there is one */
  5027.  
  5028.             while (arg[0] != NUL && arg[0] != delim)
  5029.             {
  5030.                 if (arg[0] == '\\' && arg[1] != NUL)
  5031.                     ++arg;
  5032.                 ++arg;
  5033.             }
  5034.             if (arg[0] != NUL)
  5035.                 return arg + 1;
  5036.             break;
  5037.         case CMD_and:
  5038.         case CMD_substitute:
  5039.             delim = *arg;
  5040.             if (delim)
  5041.                 ++arg;
  5042.             for (i = 0; i < 2; i++)
  5043.             {
  5044.                 while (arg[0] != NUL && arg[0] != delim)
  5045.                 {
  5046.                     if (arg[0] == '\\' && arg[1] != NUL)
  5047.                         ++arg;
  5048.                     ++arg;
  5049.                 }
  5050.                 if (arg[0] != NUL)        /* skip delimiter */
  5051.                     ++arg;
  5052.             }
  5053.             while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
  5054.                 ++arg;
  5055.             if (arg[0] != NUL)
  5056.                 return arg;
  5057.             break;
  5058.         case CMD_isearch:
  5059.         case CMD_dsearch:
  5060.         case CMD_ilist:
  5061.         case CMD_dlist:
  5062.         case CMD_ijump:
  5063.         case CMD_djump:
  5064.         case CMD_isplit:
  5065.         case CMD_dsplit:
  5066.             arg = skipwhite(skipdigits(arg));        /* skip count */
  5067.             if (*arg == '/')    /* Match regexp, not just whole words */
  5068.             {
  5069.                 for (++arg; *arg && *arg != '/'; arg++)
  5070.                     if (*arg == '\\' && arg[1] != NUL)
  5071.                         arg++;
  5072.                 if (*arg)
  5073.                 {
  5074.                     arg = skipwhite(arg + 1);
  5075.  
  5076.                     /* Check for trailing illegal characters */
  5077.                     if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
  5078.                         expand_context = EXPAND_NOTHING;
  5079.                     else
  5080.                         return arg;
  5081.                 }
  5082.             }
  5083.             break;
  5084. #ifdef AUTOCMD
  5085.         case CMD_autocmd:
  5086.             return set_context_in_autocmd(arg, FALSE);
  5087.  
  5088.         case CMD_doautocmd:
  5089.             return set_context_in_autocmd(arg, TRUE);
  5090. #endif
  5091.         case CMD_set:
  5092.             set_context_in_set_cmd(arg);
  5093.             break;
  5094.         case CMD_stag:
  5095.         case CMD_tag:
  5096.             expand_context = EXPAND_TAGS;
  5097.             expand_pattern = arg;
  5098.             break;
  5099.         case CMD_help:
  5100.             expand_context = EXPAND_HELP;
  5101.             expand_pattern = arg;
  5102.             break;
  5103.         case CMD_bdelete:
  5104.         case CMD_bunload:
  5105.             while ((expand_pattern = vim_strchr(arg, ' ')) != NULL)
  5106.                 arg = expand_pattern + 1;
  5107.         case CMD_buffer:
  5108.         case CMD_sbuffer:
  5109.             expand_context = EXPAND_BUFFERS;
  5110.             expand_pattern = arg;
  5111.             break;
  5112. #ifdef USE_GUI
  5113.         case CMD_menu:        case CMD_noremenu:        case CMD_unmenu:
  5114.         case CMD_nmenu:        case CMD_nnoremenu:        case CMD_nunmenu:
  5115.         case CMD_vmenu:        case CMD_vnoremenu:        case CMD_vunmenu:
  5116.         case CMD_imenu:        case CMD_inoremenu:        case CMD_iunmenu:
  5117.         case CMD_cmenu:        case CMD_cnoremenu:        case CMD_cunmenu:
  5118.             return gui_set_context_in_menu_cmd(cmd, arg, forced);
  5119.             break;
  5120. #endif
  5121.         default:
  5122.             break;
  5123.     }
  5124.     return NULL;
  5125. }
  5126.  
  5127. /*
  5128.  * Do the expansion based on the global variables expand_context and
  5129.  * expand_pattern -- webb.
  5130.  */
  5131.     static int
  5132. ExpandFromContext(pat, num_file, file, files_only, options)
  5133.     char_u    *pat;
  5134.     int        *num_file;
  5135.     char_u    ***file;
  5136.     int        files_only;
  5137.     int        options;
  5138. {
  5139.     regexp    *prog;
  5140.     int        ret;
  5141.     int        i;
  5142.     int        count;
  5143.  
  5144.     if (!expand_interactively || expand_context == EXPAND_FILES)
  5145.         return ExpandWildCards(1, &pat, num_file, file, files_only,
  5146.                                               (options & WILD_LIST_NOTFOUND));
  5147.     else if (expand_context == EXPAND_DIRECTORIES)
  5148.     {
  5149.         if (ExpandWildCards(1, &pat, num_file, file, files_only,
  5150.                                       (options & WILD_LIST_NOTFOUND)) == FAIL)
  5151.             return FAIL;
  5152.         count = 0;
  5153.         for (i = 0; i < *num_file; i++)
  5154.             if (mch_isdir((*file)[i]))
  5155.                 (*file)[count++] = (*file)[i];
  5156.             else
  5157.                 vim_free((*file)[i]);
  5158.         if (count == 0)
  5159.         {
  5160.             vim_free(*file);
  5161.             *file = (char_u **)"";
  5162.             *num_file = -1;
  5163.             return FAIL;
  5164.         }
  5165.         *num_file = count;
  5166.         return OK;
  5167.     }
  5168.     *file = (char_u **)"";
  5169.     *num_file = 0;
  5170.     if (expand_context == EXPAND_OLD_SETTING)
  5171.         return ExpandOldSetting(num_file, file);
  5172.  
  5173.     if (expand_context == EXPAND_HELP)
  5174.         return find_help_tags(pat, num_file, file);
  5175.  
  5176.     set_reg_ic(pat);        /* set reg_ic according to p_ic, p_scs and pat */
  5177. #ifdef AUTOCMD
  5178.     if (expand_context == EXPAND_EVENTS)
  5179.         reg_ic = TRUE;        /* always ignore case for events */
  5180. #endif
  5181.     reg_magic = p_magic;
  5182.  
  5183.     if (expand_context == EXPAND_BUFFERS)
  5184.         return ExpandBufnames(pat, num_file, file, options);
  5185.  
  5186.     prog = vim_regcomp(pat);
  5187.     if (prog == NULL)
  5188.         return FAIL;
  5189.  
  5190.     if (expand_context == EXPAND_COMMANDS)
  5191.         ret = ExpandCommands(prog, num_file, file);
  5192.     else if (expand_context == EXPAND_SETTINGS ||
  5193.                                        expand_context == EXPAND_BOOL_SETTINGS)
  5194.         ret = ExpandSettings(prog, num_file, file);
  5195.     else if (expand_context == EXPAND_TAGS)
  5196.         ret = find_tags(NULL, prog, num_file, file, FALSE);
  5197. #ifdef AUTOCMD
  5198.     else if (expand_context == EXPAND_EVENTS)
  5199.         ret = ExpandEvents(prog, num_file, file);
  5200. #endif
  5201. #ifdef USE_GUI
  5202.     else if (expand_context == EXPAND_MENUS)
  5203.         ret = gui_ExpandMenuNames(prog, num_file, file);
  5204. #endif
  5205.     else
  5206.         ret = FAIL;
  5207.  
  5208.     vim_free(prog);
  5209.     return ret;
  5210. }
  5211.  
  5212.     static int
  5213. ExpandCommands(prog, num_file, file)
  5214.     regexp        *prog;
  5215.     int            *num_file;
  5216.     char_u        ***file;
  5217. {
  5218.     int        cmdidx;
  5219.     int        count;
  5220.     int        round;
  5221.  
  5222.     /*
  5223.      * round == 1: Count the matches.
  5224.      * round == 2: Save the matches into the array.
  5225.      */
  5226.     for (round = 1; round <= 2; ++round)
  5227.     {
  5228.         count = 0;
  5229.         for (cmdidx = 0; cmdidx < CMD_SIZE; cmdidx++)
  5230.             if (vim_regexec(prog, cmdnames[cmdidx].cmd_name, TRUE))
  5231.             {
  5232.                 if (round == 1)
  5233.                     count++;
  5234.                 else
  5235.                     (*file)[count++] = strsave(cmdnames[cmdidx].cmd_name);
  5236.             }
  5237.         if (round == 1)
  5238.         {
  5239.             *num_file = count;
  5240.             if (count == 0 || (*file = (char_u **)
  5241.                          alloc((unsigned)(count * sizeof(char_u *)))) == NULL)
  5242.                 return FAIL;
  5243.         }
  5244.     }
  5245.     return OK;
  5246. }
  5247.  
  5248. #ifdef VIMINFO
  5249. static char_u **viminfo_history[2] = {NULL, NULL};
  5250. static int        viminfo_hisidx[2] = {0, 0};
  5251. static int        viminfo_hislen = 0;
  5252. static int        viminfo_add_at_front = FALSE;
  5253.  
  5254.     void
  5255. prepare_viminfo_history(len)
  5256.     int len;
  5257. {
  5258.     int i;
  5259.     int num;
  5260.     int    type;
  5261.  
  5262.     init_history();
  5263.     viminfo_add_at_front = (len != 0);
  5264.     if (len > hislen)
  5265.         len = hislen;
  5266.  
  5267.     for (type = 0; type <= 1; ++type)
  5268.     {
  5269.         /* If there are more spaces available than we request, then fill them
  5270.          * up */
  5271.         for (i = 0, num = 0; i < hislen; i++)
  5272.             if (history[type][i] == NULL)
  5273.                 num++;
  5274.         if (num > len)
  5275.             len = num;
  5276.         viminfo_hisidx[type] = 0;
  5277.         if (len <= 0)
  5278.             viminfo_history[type] = NULL;
  5279.         else
  5280.             viminfo_history[type] = (char_u **)lalloc(len * sizeof(char_u *),
  5281.                                                                        FALSE);
  5282.     }
  5283.     viminfo_hislen = len;
  5284.     if (viminfo_history[0] == NULL || viminfo_history[1] == NULL)
  5285.         viminfo_hislen = 0;
  5286. }
  5287.  
  5288.     int
  5289. read_viminfo_history(line, fp)
  5290.     char_u    *line;
  5291.     FILE    *fp;
  5292. {
  5293.     int        type;
  5294.  
  5295.     type = (line[0] == ':' ? 0 : 1);
  5296.     if (viminfo_hisidx[type] != viminfo_hislen)
  5297.     {
  5298.         viminfo_readstring(line);
  5299.         if (!is_in_history(type, line + 1, viminfo_add_at_front))
  5300.             viminfo_history[type][viminfo_hisidx[type]++] = strsave(line + 1);
  5301.     }
  5302.     return vim_fgets(line, LSIZE, fp);
  5303. }
  5304.  
  5305.     void
  5306. finish_viminfo_history()
  5307. {
  5308.     int idx;
  5309.     int i;
  5310.     int    type;
  5311.  
  5312.     for (type = 0; type <= 1; ++type)
  5313.     {
  5314.         if (history[type] == NULL)
  5315.             return;
  5316.         idx = hisidx[type] + viminfo_hisidx[type];
  5317.         if (idx >= hislen)
  5318.             idx -= hislen;
  5319.         if (viminfo_add_at_front)
  5320.             hisidx[type] = idx;
  5321.         else
  5322.         {
  5323.             if (hisidx[type] == -1)
  5324.                 hisidx[type] = hislen - 1;
  5325.             do
  5326.             {
  5327.                 if (history[type][idx] != NULL)
  5328.                     break;
  5329.                 if (++idx == hislen)
  5330.                     idx = 0;
  5331.             } while (idx != hisidx[type]);
  5332.             if (idx != hisidx[type] && --idx < 0)
  5333.                 idx = hislen - 1;
  5334.         }
  5335.         for (i = 0; i < viminfo_hisidx[type]; i++)
  5336.         {
  5337.             history[type][idx] = viminfo_history[type][i];
  5338.             if (--idx < 0)
  5339.                 idx = hislen - 1;
  5340.         }
  5341.         vim_free(viminfo_history[type]);
  5342.         viminfo_history[type] = NULL;
  5343.     }
  5344. }
  5345.  
  5346.     void
  5347. write_viminfo_history(fp)
  5348.     FILE    *fp;
  5349. {
  5350.     int        i;
  5351.     int        type;
  5352.     int        num_saved;
  5353.  
  5354.     init_history();
  5355.     if (hislen == 0)
  5356.         return;
  5357.     for (type = 0; type <= 1; ++type)
  5358.     {
  5359.         num_saved = get_viminfo_parameter(type == 0 ? ':' : '/');
  5360.         if (num_saved == 0)
  5361.             continue;
  5362.         if (num_saved < 0)    /* Use default */
  5363.             num_saved = hislen;
  5364.         fprintf(fp, "\n# %s History (newest to oldest):\n",
  5365.                             type == 0 ? "Command Line" : "Search String");
  5366.         if (num_saved > hislen)
  5367.             num_saved = hislen;
  5368.         i = hisidx[type];
  5369.         if (i >= 0)
  5370.             while (num_saved--)
  5371.             {
  5372.                 if (history[type][i] != NULL)
  5373.                 {
  5374.                     putc(type == 0 ? ':' : '?', fp);
  5375.                     viminfo_writestring(fp, history[type][i]);
  5376.                 }
  5377.                 if (--i < 0)
  5378.                     i = hislen - 1;
  5379.             }
  5380.     }
  5381. }
  5382. #endif /* VIMINFO */
  5383.